从javascript中的对象数组访问绑定函数

时间:2016-11-22 00:36:43

标签: javascript google-chrome-devtools bind

我有一个对象数组,其中包含对我的类函数的引用(由.bind()方法绑定)。当我直接访问它们时,如array[3].myFunction,一切正常。但是当我尝试访问迭代数组的这些函数时,会发生奇怪的行为。我已尝试过Array.forEach(),for-in,for-of和Array.map()函数,但结果总是一样的 - 我得到第一个函数四次。我在这做错了什么?提前谢谢。



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);
});




PLNKR:http://plnkr.co/edit/mn8iGh4F3GcJXTNWXMiJ?p=preview

1 个答案:

答案 0 :(得分:0)

看看下面。一切似乎都在起作用。

执行console.log(el.myFunction)时,它实际上会打印handle,而不是在所有句柄与function () { [native code] }相同的情况下执行它{/ 1}

当您调用函数el.myFunction()时,您可以看到他们正在调用正确的函数并分别打印结果。

您可以检查下面的函数调用。

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:');
container.array[3].myFunction();

console.log('forEach:');
container.array.forEach(el => {
  el.myFunction();
});

console.log('for in:');
for (let i in container.array) {
  container.array[i].myFunction();
}

console.log('map:')
container.array.map(el => {
  el.myFunction();
});