【问题标题】:How would you reference 'this' when the function calling 'this' is inside a child object's object?当调用“this”的函数位于子对象的对象中时,您将如何引用“this”?
【发布时间】:2015-02-17 23:41:51
【问题描述】:

我在模块(节点)内有以下设置,但这可能适用于任何地方。

function Storefront(){
    this.list = 'List';
    }

Storefront.prototype = {
    categories : {
             get : function(){
                   return this.list + ' here!';
                   }
             }
    }

module.exports = function(){
    if(!(this instanceof Storefront)) { return new Storefront(); }
    }

稍后,我在另一个模块中将对象实例化为sfront 并调用sfront.categories.get();。

通常,只需在函数内部执行var self = this;,在其中调用子函数,然后引用self,这很容易。由于显而易见的原因,这不起作用:引用“this”的对象在另一个对象内部。我不太确定如何将父对象 Storefront 的上下文传递到子对象的(类别)子属性函数“get”中。现在拉起来是'undefined',这是可以理解的。

【问题讨论】:

    标签: javascript node.js function object this


    【解决方案1】:

    您可以将categories 设为属性:

    Object.defineProperty(Storefront.prototype, 'categories', {
        get: function () {
            var storefront = this;
    
            return {
                get: function () {
                    return storefront.list + ' here!';
                }
            };
        }
    });
    

    ...这是重命名嵌套get 的一个很好的论据。但是,根据 categories 应该代表什么,将其完全设为不同的类可能更合适:

    function StorefrontCategoryList(storefront) {
        this.storefront = storefront;
    }
    
    StorefrontCategoryList.prototype.get = function () {
        return this.storefront.list + ' here!';
    };
    
    function Storefront() {
        this.list = 'List';
        this.categories = new StorefrontCategoryList(this);
    }
    

    【讨论】:

    • 是的,这正是我正在考虑的;我不确定我当前的设置是否有办法做到这一点。我当然会重命名 get 函数。 @zerkms:在 Node 中,每个模块都被缓存并在以后调用该模块时返回相同的对象。
    • @zerkms:我不确定 IIFE,但 bind() 可以做到。
    • 不要考虑 that(或 self),而是考虑指示 that 是什么的东西,例如 var storeFront = this。
    • @RobG:我实际上称它为self,就像问题中一样。 storefront 更好,是的。
    • 我想这都是语义,但 self 对我来说也没有多大意义。 :-(
    【解决方案2】:

    在对象字面量中定义getter。

    function Storefront(){
        this.list = 'List';
    } 
    Storefront.prototype = {
        get categories () {
            var self = this;
            return {
                "get": function () {
                    return self.list + ' here!';
                }
            };
        }
    };
    (new Storefront()).categories.get(); // "List here!"
    

    虽然您无法设置为foo.categories,但您现在可以轻松引用该实例。

    这种方式会使用更多的cycles,另一种方法是直接给每个实例自己的categories属性(可以有不同的继承链),但是会使用更多内存

    【讨论】:

    • 这是真的 - 如果我不将 foo.categories 设置为另一个对象,这肯定会起作用;但随着更多模块的构建以及将内部对象作为独立对象引用变得更加合适,这可能会出现。不过,这是对原始问题的一个很好、简单的答案!
    猜你喜欢
    • 2019-05-19
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2019-09-11
    • 1970-01-01
    相关资源
    最近更新 更多