簡體   English   中英

當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 作為一種變通方法,您可以簡單地替換thisa

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM