【问题标题】:Confuse about ES5′s array extra methods' context混淆 ES5 的数组额外方法的上下文
【发布时间】:2013-08-28 07:38:04
【问题描述】:

我尝试使用一些 ES5 的数组额外方法,例如 mapsomeforEach

[1, 2, 3].forEach(function (el) {
    console.log(this) // window
})

但我发现这些方法中的上下文不是调用它们的数组

但是Global contextwindow

在 MDN 的 opinion

当一个函数作为一个对象的方法被调用时,它的 this 被设置为 调用该方法的对象。

那么数组和被调用方法之间究竟是什么关系呢?

【问题讨论】:

  • 匿名回调函数不是Array的方法,forEach()是。

标签: arrays function ecmascript-5


【解决方案1】:

如果您查看on the developer.mozilla.org,您会看到forEach 的签名是:

array.forEach(callback[, thisArg])

然后

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

所以你永远不会收到array 作为this,除非你把它作为forEach 的第二个参数。

【讨论】:

    【解决方案2】:

    this 设置为 forEach 方法中调用 forEach 的数组。但是,您传递给 forEach 方法的匿名函数没有将其 this 设置为数组,因为该函数没有作为数组上的方法调用。 (但您可以将数组作为thisArg 提供给forEach 方法,因此匿名函数中的this 将指向该数组。

    例子:

    var a = [1, 2, 3];
    a.forEach(function (el) {
        console.log(this) // the Array
    }, a);
    

    或绑定函数:

    var a = [1, 2, 3];
    a.forEach((function (el) {
        console.log(this) // the Array
    }).bind(a));
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多