假设我有这样的代码:
var object1 = {};
object1.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
在这种情况下,“this”代表什么? object1 还是 class1?每当我想在对象中定义类构造函数时,最好的方法是什么?
最佳答案
对于class1
,因为你不能创建object1类型的对象。
但是,如果代码是:
function object1() {
this.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
}
你可以:
var obj = new object1();
obj.class1();
obj.property2; // => 'ab';
var cls = new obj.class1();
cls.property2; // => 'ab';
所以这可能取决于上下文。
关于javascript 'this' 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3520014/