2

I try to define prototype functions from an array. As in the following example : my black rabbit should say 'toto' but it doesn't say it ! Why ?

function Rabbit ( type ) {
    this.type = type ;
}

var funcs = ["says", "doesnt_say"];

for(var i=0;i<funcs.length;i++)
{
    var f = funcs[i];
    Rabbit.prototype[f] = function ( line ) {
        alert(" The " + this.type + " rabbit " 
              + f + "  '" + line + " '") ;
    };
}

var blackRabbit = new Rabbit ("black") ;
blackRabbit.says("toto");

Visible on http://jsfiddle.net/xou11bgu/

turbo
  • 1,233
  • 14
  • 36
flojug
  • 21
  • 3

2 Answers2

1

The problem is that the variable "f" is shared by all the functions you create, and it will end up having the value of the last function name.

You can use a function to construct the functions:

Rabbit.prototype[f] = function(f) {
    return function ( line ) {
        alert(" The " + this.type + " rabbit " 
              + f + "  '" + line + " '") ;
    };
}(f);

This is an instance of an extremely common JavaScript stumbling block; there are many, many other similar questions here on Stackoverflow, but they're hard to find because until you know what the problem is it's hard to know what you're looking for.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

You are using the variable f in the method, but that variable is shared by all methods and will contain the name of the last method.

You can use a function to create a scope where each method will gets its own variable f:

for(var i=0;i<funcs.length;i++) {
  (function(f){
    Rabbit.prototype[f] = function ( line ) {
      alert("The " + this.type + " rabbit " + f + " '" + line + "'") ;
    };
  })(funcs[i]);
}

Demo: http://jsfiddle.net/xou11bgu/4/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005