javascript - 当调用 'this' 的函数位于子对象的对象内部时,您将如何引用 'this'?

标签 javascript node.js function object this

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

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',这是可以理解的。

最佳答案

您可以将类别设为属性:

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);
}

关于javascript - 当调用 'this' 的函数位于子对象的对象内部时,您将如何引用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27559236/

相关文章:

javascript - 如何仅在 IE 中强制打开新窗口

javascript - YouTube 嵌入视频在动态更新 iframe src 时停止播放

delphi - 数组作为结果类型和函数输入

javascript - 使用按钮将文本写入输入框

javascript - 检查函数参数是否为 JavaScript 中的默认参数

javascript - 为什么这种 CSS 样式会干扰 HTML5 拖放? (位置: absolute; left: -10000px)

javascript - 加载 React 组件后,如何调用 javascript 文件中存在的函数?

node.js - Nuxt run dev fatal error ,状态码 500

javascript - 在返回 promise 中执行 .then()

node.js - 你如何修改 generator-angular-fullstack 图标?