属性别名的最佳方法是什么?

时间:2013-10-08 20:42:17

标签: javascript object methods

我处于这样一种情况,即必须能够通过两个不同的名称来调用对象上的方法,而我发现这样做的最短路径是这样的:

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

我当时希望有这样的事情:

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

但到目前为止,我的研究并没有发生过类似的事情。还有更好的办法吗?

4 个答案:

答案 0 :(得分:6)

您可以稍后再分配:

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

c.b = c.a;

答案 1 :(得分:2)

我担心在JS中只使用一个语句就没有好办法,但是你可以在一个闭包内完成它,这是大多数JS模块所做的。

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

答案 2 :(得分:2)

你可以使用构造函数

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

c = new d();

DEMO fiddle

答案 3 :(得分:1)

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

尽管看起来可能如此,但c并未引用某个函数,而是一个具有ab属性的新对象。

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

如果您需要这个来创建多个对象,那么命名版本更有意义。

相关问题