执行属性别名的最佳方法

Best way to do property aliasing?

本文关键字:最佳 方法 别名 属性 执行      更新时间:2023-09-26
我的情况是,必须

能够通过两个不同的名称在对象上调用方法,我发现这样做的最短方法是这样的:

var c = {
    a : function() {console.log("called a!");}.
    b : function() {this.a();}
};

我宁愿希望有这样的东西:

var c = {
    a,b : function() {console.log("called a!");}.
};

但到目前为止,我的研究还没有发生过这样的事情。有没有更好的方法?

你可以稍后分配 b:

var c = {
    a : function() {console.log("called a!");}.
};
c.b = c.a;

怕只使用一个语句在 JS 中没有好方法可以做到这一点,但你可以在闭包中完成它,这是大多数 JS 模块所做的。

var c = (function () {
    var a = function() {console.log("called a!");};
    return {
        'a': a,
        'b': a
    };
}());

您可以使用构造函数

function d(){
    this.a = this.b = function() {console.log("to c or not to c?");};
}
c = new d();

演示小提琴。

var c = new function() {
    this.a = this.b = function() {console.log("called a!");}.
};

尽管看起来很像,但c引用的不是函数,而是具有ab属性的新对象。

此外,没有额外的命名空间混乱。

如果需要它来创建多个对象,则命名版本更有意义。