如何扩展javascript对象?

Nat*_*tim 5 javascript

我用babel对象做了一个简单的问题示例:

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

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

babel.prototype.french = {
    bonjour: function () { alert('bonjour'); },
    aurevoir: function () { alert('au revoir'); }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我能做的是:

var say = new babel();

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

但是在这种情况下,我会一直使用say对象的上下文,不是吗?

Krz*_*tof 4

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

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

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你的法语将如下所示:

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