javascript - 如何扩展一个javascript对象?

标签 javascript

我用 babel 对象做了一个简单的例子来说明我的问题:

function babel(){
    this.english = {
        hello: function () { alert('hello'); },
        goodbye: function () { alert('goodbye'); }
        teeshirt: function () { alert('T-shirt'); }
    }
}

现在,我想扩展这个对象:

babel.prototype.french = {
    bonjour: function () { alert('bonjour'); },
    aurevoir: function () { alert('au revoir'); }
}

但是如果我需要使用之前定义的现有函数怎么办?

babel.prototype.french = {
    bonjour: function () { alert('bonjour'); },
    aurevoir: function () { alert('aurevoir'); },
    teeshirt: function () { this.english.teeshirt(); }
}

我能做的是:

var say = new babel();

(function (_this) {
    babel.prototype.french = {
    bonjour: function () { alert('bonjour'); },
    aurevoir: function () { alert('aurevoir'); },
    hello: function () { _this.english.hello(); }
    }
})(say);

但在这种情况下,我将始终使用 say 对象的上下文,不是吗?

最佳答案

问题是,在 teeshirt 函数中调用 this 指向的是 french 对象,而不是 babel 对象。如果你必须访问父对象,你应该在某处存储对它的引用。例如,您可以像这样更改您的构造函数:

function babel(){
    this.english = {
        parent: this,
        hello: function () { alert('hello'); },
        goodbye: function () { alert('goodbye'); }
        teeshirt: function () { this.parent.french.something(); }
    }
}

但是如您所见,如果您不在构造函数中创建对象,就会出现问题。我没有看到任何“好的”方法,但你可以这样做:

function babel(){
    this.english = {
        parent: this,
        hello: function () { alert('hello'); },
        goodbye: function () { alert('goodbye'); }
        teeshirt: function () { this.parent.french.something(); }
    };
    for (var i in babel.prototype) {
        this[i].parent = this;
    }
}

然后你的法语看起来像这样:

babel.prototype.french = {
    bonjour: function () { alert('bonjour'); },
    aurevoir: function () { alert('aurevoir'); },
    teeshirt: function () { this.parent.english.teeshirt(); }
}

关于javascript - 如何扩展一个javascript对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374046/

相关文章:

javascript - ionic /Angular : HTML doesnt display information from ts file

javascript - Android浏览器Javascript onclick事件未收到回调

javascript - 将 Canvas 绘制到另一个 Canvas 上不起作用

javascript - 我目前正在尝试在将任务添加到数组后清除输入字段

javascript - 将变量传递给函数回调

javascript - angularjs 预检响应具有无效的 HTTP 状态代码 404

javascript - Ng-repeat 不同的单选按钮组

javascript - React中如何将数据从子组件发送到父组件

Javascript Google Charts 更改数据

javascript - 如何避免在for循环完成之前调用.map函数?