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
.
精彩评论