我必须从子对象“object3”调用“object1”中的属性,但是此示例不起作用,因为“this”关键字在“object2”而不是“object1”中引用,你知道如何这样做?
function object1() {
this.a = "hello world";
this.object2 = function() {
this.object3 = function() {
alert(this.a); //prints "undefined"
}
};
}
尝试使用以下示例:
var obj1 = new object1();
var obj2 = new obj1.object2();
obj2.object3();
提前谢谢: - )
答案 0 :(得分:1)
function object1() {
this.a = "hello world";
var self = this;
this.object2 = function () {
this.object3 = function () {
alert(self.a); //prints "undefined"
}
};
}
var obj1 = new object1();
var obj2 = new obj1.object2();
obj2.object3();
您必须存储this
对象,否则您将访问函数this
范围的this.object3
答案 1 :(得分:0)
this
会发生变化。您需要为任何新范围保存this
的引用:
function object1 () {
var first_scope = this;
this.a = "hello world";
this.object2 = function() {
var second_scope = this;
this.object3 = function() {
var third_scope = this;
alert(first_scope.a);
}
};
}