我在 JS 中遇到一个小问题,我有两个嵌套对象,我想从父对象访问一个变量,如下所示:
var parent = {
a : 5,
child: {
b : 3,
displayA : function(){
console.log(this.a);
//undefined
},
displayB : function(){
console.log(this.b);
//displays 3
}
}
}
我只想知道如何使parent.child.displayA 工作:)(我有需要访问父级变量的子对象)
任何帮助表示赞赏
非常感谢!
您可以使用call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call设置值this
:
parent.child.displayA.call(parent); // 5
您也可能对。。。有兴趣binding https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind it:
parent.child.displayA = function(){
console.log(this.a);
}.bind(parent);
parent.child.displayA(); // 5
或者你可以使用parent
代替this
:
parent.child.displayA = function(){
console.log(parent.a);
};
parent.child.displayA(); // 5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)