开发者

How to resolve 'this' keyword within nested object literals

开发者 https://www.devze.com 2023-03-31 05:18 出处:网络
I am trying organize object literal code as such. Is there a clean/efficient way to point \'this\' in the inner function which points to开发者_StackOverflow社区 \'category\' to \'obj\'?

I am trying organize object literal code as such. Is there a clean/efficient way to point 'this' in the inner function which points to开发者_StackOverflow社区 'category' to 'obj'?

var obj = {
    outerFunc : function () {
        console.log(this);
    },
    outer_prop : 1,
    category : {
        innerFunc : function () {
            console.log(this);
        },
        inner_prop : 2
    }
};

var my_obj = Object.create(obj);
my_obj.outerFunc();
my_obj.category.innerFunc();


You can invoke your innerFunc with the call() method, to which you can pass what you want this to be:

my_obj.category.innerFunc.call(obj);
0

精彩评论

暂无评论...
验证码 换一张
取 消