0

我可以在 for 循环中创建多个函数吗?

var mySound1 = new buzz.sound( "laser-01", { formats: [ "ogg", "mp3", "acc" ]});
var mySound2 = new buzz.sound( "alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]});

var sound = [mySound1, mySound2]

// additional sounds
var $i;
for ( $i = 0; $i< sound.length; $i++){
    function playsound[$i](){   
           a[$i].play().fadeIn().loop();
        }
}

playsound1();
4

2 回答 2

3

您可以重用一个功能:

// 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(); 
于 2012-12-03T03:28:31.703 回答
1

您最好将 $i 作为参数传递给 playsound 函数

var sounds = [
    new buzz.sound( "laser-01", { formats: [ "ogg", "mp3", "acc" ]}),
    new buzz.sound( "alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]})
];

var playsound = function (i) {   
   sounds[i].play().fadeIn().loop();
}

playsound(1);

如果你真的想要playsound1()样式函数名称,你可以评估它(尽管我建议不要添加这个):

for (var i = 0; i < sounds.length; i++){
    eval('var playsound' + (i+1) + ' = function() { playsound(' + i + '); };');
}

playsound1();
playsound2();
于 2012-12-03T03:24:11.383 回答