Array.prototype.map中的'thisArg'参数

时间:2018-01-25 06:14:02

标签: javascript this

关于Array.prototype.map

mdn document如下所示

  

arr.map(callback[, thisArg])
  如果提供thisArg参数进行映射,则它将用作回调的此值。否则,undefined值将用作此值。最终通过回调可观察到的这个值是根据确定函数所见的通常规则来确定的。

什么是this值,undefined或其他通常规则确定的值?

此外,在课堂上使用时,this的回调中的Array.mapundefined

class Sample {
  constructor() {
    this.list = [1, 2, 3];
  }
  mapList() {
    this.list.map(function(x) {
      console.log(this); 
    });
  }
}
const obj = new Sample();
obj.mapList();    // `this` is undefined

但是在使用函数时它是窗口。尽管this值相同,但为什么thisArgs在两种情况下会有所不同?

function Sample() {
  this.list = [1, 2, 3];
}
Sample.prototype.mapList = function() {
  return this.list.map(function(x) {
    console.log(this); 
  });
}
const obj = new Sample();
obj.mapList();  // `this` is window(global object)

我知道这是一个经常被问到的问题,有些用户会将此问题视为重复,但由于理解不充分,我不得不提出这个问题。

我只是想知道为什么在上面使用类的代码中未定义this,而不是解决方案(bindarrow funtion事物)。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

来自MDN

  

类声明和类表达式的主体在中执行   严格模式,即构造函数,静态和原型方法,getter和   setter函数以严格模式执行。

在严格模式上下文中,如果未指定未定义。

  

...在严格模式下传递给函数的值不会强制成为对象(a.k.a。“boxed”)   ...因此对于严格模式函数,指定的不会被装入   一个对象,如果没有指定,这将是未定义的

如果您将"use strict"添加到第二个示例,它也将是undefined