0

I am trying to generate objects containing functions that are using other object attributes. It's a bit difficult to explain so let me give an example:

I've written that code:

var myarray = [
    {name: "n1"},
    {name: "n2"},
    {name: "n3"},
    {name: "n4"},
    {name: "n5"},
];
var printers = [];
for (index=0;index<5;index++) {
    var obj = myarray[index];
    printers[index] = {
        myfunc : function(titi, tata) {
            console.log("name: " + obj.name);
        }
    }
}
for (index=0;index<printers.length;index++) {
    printers[index].myfunc();
}

When I execute the code, I get that result:

name: n5
name: n5
name: n5
name: n5
name: n5

What I need is:

name: n1
name: n2
name: n3
name: n4
name: n5

I would be glad if someone out there could help me understand how you can manage this in javascript.

Alexandre Mélard
  • 12,229
  • 3
  • 36
  • 46

1 Answers1

1

Try this

printers[index] = {
    myfunc : function (name) {
       return function(titi, tata) {
        console.log("name: " + name);
       }
    }(obj.name)
}

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144