这个Arg-in.forEach的目的是什么

What is the purpose of thisArg in .forEach?

本文关键字:是什么 forEach Arg-in 这个      更新时间:2023-09-26

JavaScript的forEach文档指出.forEach语法为:

arr.forEach(callback[, thisArg])

thisArg的用途是什么?

可以提供thisArg来更改回调函数的内部this

不指定thisArg导致this在非严格模式下引用Window。在严格模式("use strict";)中,它将是undefined



如果您对以下事实感到困惑,thisArg在使用箭头函数时不会执行任何操作

var myObject = { name: 'myObject' };
[1,2].forEach(item => { 
  console.log(item);                     // 1, 2
  console.log(this === myObject, this);  // false  Window {}
}, myObject)

这是因为:

无法绑定箭头函数

在箭头函数中,如果没有作用域提供this值,则this指代最接近作用域的this,一直到Window。它的工作方式就像普通的变量查找一样,直到找到一些this
为了更好地理解this,请参阅本要点或运动场



具有正常功能的上下文绑定

var myObject = { name: 'myObject' };
[1,2].forEach(function(item){ 
  console.log(item);                     // 1, 2
  console.log(this === myObject, this);  // true  {name: "myObject"}
}, myObject)

如果此时未指定myObject,则内部的this将与箭头函数一样指向Window

thisArg是指应该调用回调的上下文,基本上就是CCD_ 20在回调中所指的。例如:

var myObject = { name: 'myObject' };
[1,2].forEach(function(item) { 
 console.log(item); // 1, 2
 console.log(this === myObject); // true
}, myObject)

this值是一个与execution context相关的特殊对象。

一个对象,在该对象的上下文中,执行上下文被激活

this的值在进入上下文时仅确定一次并且不可能为这个分配新的值

在您的情况下,提供thisArg就像

arr.forEach(callback.bind(thisArg));

forEach,为您简化了它,要求单独的可选参数

现在,如果您在没有this 的情况下运行此forEach

arr.forEach(function(item) {
    console.log(this === window); //true
    console.log(this === arr);    //false
});

你明白了!

我认为这些测试会让整个事情变得清楚只需在浏览器控制台中进行测试

arr=[0];
arr.forEach(function(item) {
    console.log(this === window); //true
    console.log(this === arr);    //false
});
arr.forEach(function(item) {
    console.log(this === window); //true
    console.log(this === arr);    //false
},this);
arr.forEach(function(item) {
    console.log(this === window); //false
    console.log(this === arr);    //true
},arr);
arr.forEach(function(item) {
    console.log(this === window); //false
    console.log(this === arr);    //false
},0);

我经常在原型和函数的上下文中使用这个:

var MyClass = function() {
  this.GlobalVar = 3;
}
MyClass.prototype.func1 = function(a) {
  return (a == this.GlobalVar);
}
MyClass.prototype.func2 = function(arr) {
  arr.forEach(function(item) {
    console.log(this.func1(item));
  }, this); // use of thisArg
}
MyClass.prototype.func3 = function(arr) {
  var that = this;
  arr.forEach(function(item) {
    console.log(that.func1(item));
  }); // also possible without using thisArg
}
MyClass.prototype.func4 = function(arr) {
  arr.forEach(function(item) {
    console.log(this.func1(item));
  }); // implementation raising an error, because this.func1 does not exist in that context
}
var arr = [0, 1, 3, 4, 3, 1];
var myClass = new MyClass();
myClass.func2(arr);
/* prints:
false
false
true
false
true
false
*/
myClass.func3(arr) /* same as func2 */
myClass.func4(arr); /* Fails with
Error: {
  "message": "TypeError: this.func1 is not a function",
  "filename": "https://stacksnippets.net/js",
  "lineno": 35,
  "colno": 26
}
*/