您可以重用一个功能:
// 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();