简体   繁体   中英

When JavaScript object literal nested, what the this is?

I have a object a :

var a = {
    b: {
        f1: function(){console.log('in a.b.f1')}
    },
    c: {
        _this: this,
        f2: function(){this._this.b.f1()}
    }
}

then, I found the error TypeError: Cannot call method 'f1' of undefined

How should I call abf1() in acf2 ?

The answer is in the question, use abf1() .

By default, this refers to the object which owns the function. If the function is "free", this refers to the global window object. If this is not wrapped inside a function, it refers to window as well.

// "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" */ }

Knowing this and considering your code, we can say that this does not refer to a since it's not contained in a function owned by a . As a workaround, you could simply replace this with a :

var a = {};
a.b = {
    f1: function () { console.log('in a.b.f1'); }
};
a.c = {
    parent: a,
    f2: function () { this.parent.b.f1(); }
};

Notice that you can "redirect" this to another object using call() or apply() :

o.child.f.call(o); // "this" is now "o" inside of "o.child.f"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM