我設置了一個對象構造函數,並希望將一個鍵/值對象作爲參數傳遞。我想知道什麼纔是正確的方法呢?現在,我只是路過的鍵作爲參數:在JavaScript構造函數中傳遞鍵/值對象作爲參數
(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中做到這一點?我現在寫的東西的方式讓我感覺好像我膨脹我的constructer的參數列表(除非這個是正確的方式來做到這一點)。
可以通過在一個如果這就是你要求的對象參數而不是多個原語。不太清楚你想要做什麼 – charlietfl