I have an array of objects containing references (bound by the .bind()
method) to my class functions. When I access them directly, like array[3].myFunction
, everything works fine. But the strange behavior occurs when I try to access these function iterating over the array. I've tried by Array.forEach()
, for-in, for-of and Array.map()
function, but the result is always the same - I get the first function four times. What am I doing wrong here? Thanks in advance.
var Container = function() {
this.function1 = function() {
console.log('function 1 invoked');
};
this.function2 = function() {
console.log('function 2 invoked');
};
this.function3 = function() {
console.log('function 3 invoked');
};
this.function4 = function() {
console.log('function 4 invoked');
};
this.array = [
{ key: '1', myFunction: this.function1.bind(this) },
{ key: '2', myFunction: this.function2.bind(this) },
{ key: '3', myFunction: this.function3.bind(this) },
{ key: '4', myFunction: this.function4.bind(this) },
];
};
var container = new Container();
// Just printing the results below
console.log('direct access:');
console.log(container.array[3].myFunction);
console.log('forEach:');
container.array.forEach(el => {
console.log(el.myFunction);
});
console.log('for in:');
for (let i in container.array) {
console.log(container.array[i].myFunction);
}
console.log('map:')
container.array.map(el => {
console.log(el.myFunction);
});