The invocation context (this) of the forEach funct

2019-01-05 03:53发布

I was wondering what the 'this' value (or invocation context) is of the forEach callback function. This code doesn't seem to work:

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

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

    this[i] = v + 1;

});

alert(jow);

Thx for explaining it to me.

4条回答
\"骚年 ilove
2楼-- · 2019-01-05 04:16

If you dont pass second parameter to forEach, this will point to the global object. To achieve what you were trying to do

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

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

console.log(jow);

Output

[ 6, 11, 46, 68 ]
查看更多
再贱就再见
3楼-- · 2019-01-05 04:23

MDN states:

array.forEach(callback[, thisArg])

If a thisArg parameter is provided to forEach, it will be used as the this value for each callback invocation as if callback.call(thisArg, element, index, array) was called. If thisArg is undefined or null, the this value within the function depends on whether the function is in strict mode or not (passed value if in strict mode, global object if in non-strict mode).

So in short, if you only provide the callback and you're in non-strict mode (the case you presented), it will be the global object (window).

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

查看更多
狗以群分
4楼-- · 2019-01-05 04:25

I finished construction of the forEach method and wanted to share this diagram with everyone, hope it helps someone else trying to understand its inner workings.

The forEach method

查看更多
神经病院院长
5楼-- · 2019-01-05 04:30

Inside forEach, this refers to the global window object. This is the case even if you call it from a different object (i.e. one you've created)

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
查看更多
登录 后发表回答