forEach函数调用的调用上下文(this)

问题描述 投票:25回答:5

我想知道forEach回调函数的'this'值(或调用上下文)是什么。此代码似乎不起作用:

var jow = [5, 10, 45, 67];

jow.forEach(function(v, i, a){

    this[i] = v + 1;

});

alert(jow);

谢谢你向我解释。

javascript function foreach this invocation
5个回答
43
投票

MDN声明:

array.forEach(callback [,thisArg])

如果向forEach提供thisArg参数,则它将用作每个回调调用的this值,就像调用callback.call(thisArg,element,index,array)一样。如果thisArg未定义或为null,则函数中的此值取决于函数是否处于严格模式(如果处于严格模式则传递值,如果处于非严格模式则传递全局对象)。

简而言之,如果你只提供回调并且你处于非严格模式(你提出的情况),那么它将是全局对象(窗口)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach


10
投票

我完成了forEach方法的构建,并希望与大家分享这个图表,希望它能帮助其他人试图了解其内部工作原理。


4
投票

在forEach中,this指的是全球window对象。即使您从另一个对象(即您创建的对象)调用它也是如此

window.foo = 'window';

var MyObj = function(){
  this.foo = 'object';
};

MyObj.prototype.itirate = function () {
  var _this = this;

  [''].forEach(function(val, index, arr){
    console.log('this: ' + this.foo); // logs 'window'
    console.log('_this: ' + _this.foo); // logs 'object'
  });
};

var newObj = new MyObj();

newObj.itirate();
// this: window
// _this: object

3
投票

如果你没有将第二个参数传递给forEachthis将指向全局对象。实现你想要做的事情

var jow = [5, 10, 45, 67];

jow.forEach(function(v, i, a) {
    a[i] = v + 1;
});

console.log(jow);

产量

[ 6, 11, 46, 68 ]

0
投票

对于'this'上下文问题,我有一个非常简单的方法,它是这样的:每当你想知道'this'的上下文是什么时,如果左边没有调用者,请检查谁留给调用者。是对象实例的全局其他:

例子:

let obj = { name:"test", fun:printName }

function printName(){
  console.log(this.name)
}

//who is left to the caller? obj! so obj will be 'this'
obj.fun() //test

//who is left to the caller? global! so global will be 'this'
printName() //undefined (global has no name property)

因此,对于'foreach'情况,当您提供回调函数时,foreach实现中实际发生的事情是这样的:

- >你打[1,2,3] .foreach(回调,'可选这个')

 foreach(arr,cb)
 {
  for(i=0; i<arr.len;i++)
  {
   //who is left to the caller? global! so it will be 'this'
   cb(arr[i])
  }
 }

除非 - 你给它选择'this'或你用一个this(例如箭头函数)绑定回调,如果发生这种情况比被调用的回调已经有一个'this'obj那种'阻止'你改变它的给定上下文更多关于绑定可以在这里找到enter link description here但基本上绑定实现看起来如下:

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

所以你可以看到你的'this'(范围)总是会调用fn(你的回调)

希望能帮助到你...

© www.soinside.com 2019 - 2024. All rights reserved.