我正在设置一个对象构造函数,并希望将键/值对象作为参数传递。我想知道这样做的正确方法是什么?现在我只是将 key 作为参数传递:
(function() {
function Venue(name, poor, satisfactory, excellent) {
this.name = name;
this.serviceRatings = {
poor: poor,
satisfactory: satisfactory,
excellent: excellent
};
}
var dining = new Venue("dining", .1, .15, .2);
console.log(dining["serviceRatings"]["satisfactory"] // .15
}());
虽然这可行,但从 Ruby 背景来看,只觉得传递对象本身并在初始化器中分配它的值是正确的。这是我能想到的最好的等价物:
class Venue
def initialize(name, serviceRatings = {})
@name = name
@poor = serviceRatings[:poor]
@satisfactory = serviceRatings[:satisfactory]
@excellent = serviceRatings[:excellent]
end
end
有没有办法在 JavaScript 中做到这一点?我现在编写内容的方式让我感觉好像我的构造函数的参数列表正在膨胀(除非这是正确的方法)。
最佳答案
您可以传递一个对象,就像在 ruby 类中所做的那样。
function Venue(name, options) {
this.name = name;
this.serviceRatings = options;
}
var dining = new Venue("dining",{
poor: .1,
satisfactory: .15,
excellent: .2
});
上面将创建与以前相同的输出。值得一提的是 ecmascript 2015 为 javascript 带来了类 - 所以你也可以这样写:
class Venue {
constructor(name, options = {}) {
this.name = name;
this.serviceRatings = options;
}
}
上面我们使用一个空对象作为默认参数
,这也是 es2015 的一个特性。
如果你想有默认的键名,类似这样的东西就可以了
class Venue {
constructor(name, options = {}) {
this.name = name;
this.serviceRatings = Object.assign({
poor: undefined,
satisfactory: undefined,
excellent: undefined
}, options);
}
}
关于javascript - 在 Javascript 构造函数中将键/值对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113809/