![](/img/trans.png)
[英]What do people mean when they say “object literal” in JavaScript?
[英]When JavaScript object literal nested, what the this is?
我有一個對象a
:
var a = {
b: {
f1: function(){console.log('in a.b.f1')}
},
c: {
_this: this,
f2: function(){this._this.b.f1()}
}
}
然后,我發現錯誤TypeError: Cannot call method 'f1' of undefined
我應該如何在acf2
調用abf1()
?
答案是在問題中,使用abf1()
。
默認情況下, this
是指擁有該功能的對象。 如果該功能是“免費的”, this
指的是全局window
對象。 如果this
是不是一個函數里面包裹着,它指的是window
為好。
// "this" is window
function f() { /* "this" is "window" */ }
var o = {};
o.f = function () { /* "this" is "o" */ }
o.child = {};
o.child.f = function () { /* "this" is "o.child" */ }
知道了這一點,並考慮你的代碼,我們可以說, this
並不是指a
,因為它不是由擁有的功能包含a
。 作為一種變通方法,您可以簡單地替換this
有a
:
var a = {};
a.b = {
f1: function () { console.log('in a.b.f1'); }
};
a.c = {
parent: a,
f2: function () { this.parent.b.f1(); }
};
請注意,您可以在“重定向” this
使用到另一個對象call()
或apply()
o.child.f.call(o); // "this" is now "o" inside of "o.child.f"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.