gpt4 book ai didi

javascript - 如何使用 "this"关键字从子对象引用属性

转载 作者:行者123 更新时间:2023-11-30 05:47:34 25 4
gpt4 key购买 nike

我必须从子对象“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();

提前谢谢你:-)

最佳答案

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的范围

关于javascript - 如何使用 "this"关键字从子对象引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17121767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com