您可以重複使用的功能:
// declare your sound dictionary
var sounds = {
'laser': new buzz.sound("laser-01", { formats: [ "ogg", "mp3", "acc" ]}),
'alien-noise': new buzz.sound("alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]})
};
// this is the helper function
var playSoundFn = function() {
this.play().fadeIn().loop();
};
// assign the helper function to all your sounds
for (var i=0, len=sounds.length; i<len; i++){
sounds[i].playSound = playSoundFn;
}
// then play your sounds from any of them in your dictionary :
sounds['laser'].playSound();
sounds['alien-noise'].playSound();
** 編輯 **(感謝TheSmose)
如果sounds
陣列中的每個項目都與buzz.sound.prototype
原型創建的,那麼你可以簡單地添加自定義功能,並簡單地使用它:
// this is the helper function
buzz.sound.prototype.playSound = function() {
this.play().fadeIn().loop();
};
// declare your sound dictionary
var sounds = {
'laser': new buzz.sound("laser-01", { formats: ["ogg", "mp3", "acc"]}),
'alien-noise': new buzz.sound("alien-noise-01", {formats: ["ogg", "mp3", "acc"]})
};
// then play your sounds from any of them in your dictionary :
sounds['laser'].playSound();
sounds['alien-noise'].playSound();
什麼是'a'?你的意思是'聲音[$ i]'? –
函數名必須是一個標識符,所以語法根本不起作用。此外,因爲所有這些假設的函數將共享相同的變量'$ i',他們將不會做你需要的。這是Stackoverflow上數千次問題的變體。 – Pointy