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

3

我遇到了一个需要在对象上通过两个不同的名称调用方法的情况,目前我发现最简短的解决方法如下:

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

我非常希望有这样的东西存在:

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

但是我目前的研究还没有找到类似的东西。有更好的方法吗?
4个回答

6
您可以稍后分配b:
var c = {
    a : function() {console.log("called a!");}.
};

c.b = c.a;

简洁明了,但可能不是最优的组织方案。等待其他更好的选择。 - temporary_user_name

2
抱歉,用一句JS语句来解决这个问题似乎没有好的方法,但是你可以在闭包中完成它,这也是大多数JS模块的做法。
var c = (function () {
    var a = function() {console.log("called a!");};
    return {
        'a': a,
        'b': a
    };
}());

这太完美了。我不知道我可以做到这一点。事实上,我真的很想了解更多关于这个的内容,但我不确定如何...你知道在JS中使用返回语句与逗号分隔的方法/属性关联系列的术语是什么吗? - temporary_user_name
@Aerovistae:这只是一个返回带有属性的对象的函数。虽然看起来比你的“最短方式”要长。 - user2736012

2
你可以使用构造函数。
function d(){
    this.a = this.b = function() {console.log("to c or not to c?");};
}

c = new d();

演示代码


1
这样写更好:this.a = this.b = function() {console.log("called a!");},对吧? - Yuriy Galanter
1
到目前为止,这是我最喜欢的解决方案。精确而封装。 - Yuriy Galanter

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

虽然看起来像是引用了一个函数,但实际上c是一个具有ab属性的新对象。
此外,没有额外的命名空间混乱。
如果需要创建多个对象,则使用命名版本更合理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接