开发者

javascript 'this' usage

let's say I have code like this:

var object1 = {};
object1.class1 = function() {
    this.property1 = null;
    this.property2 = 'ab';
}

in this case, what does 'this' stand for? object1 or class1开发者_如何学C? And whenever I want to define a class constructor inside an object, what is the best way to do it?


For class1, because you can't make an object of type object1.

However, if the code would be:

function object1() {
    this.class1 = function() {
        this.property1 = null;
        this.property2 = 'ab';
    }
}

You could have:

var obj = new object1();
obj.class1();
obj.property2; // => 'ab';

var cls = new obj.class1();
cls.property2; // => 'ab';

So it could depend on context.


If you call it like so:

object1.class1();

Then this will refer to object1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜