为什么我的函数的 es6 版本说"Cannot read property 'forEach' of undefined"



这个版本的es6函数不起作用:

Array.prototype.concatAll = () => {
  let results = [];
  this.forEach((subArray) => {
    subArray.forEach((item) => {
      results.push(item);
    });
  });
  return results;
};

当我这样使用它时:

var stocks = exchanges.concatAll();

控制台显示:Cannot read property 'forEach' of undefined

然而,这个es5版本运行得很好:

Array.prototype.concatAll = function() {
  let results = [];
  this.forEach((subArray) => {
    subArray.forEach((item) => {
      results.push(item);
    });
  });
  return results;
};

为什么会这样?es6版本中的this究竟发生了什么?我想了解。

这已经提到了,但对于箭头函数来说,这不是一个好的用例,因为它们绑定了this的值。使用ES6执行此操作的另一种方法是使用Object.assign

例如:

Object.assign(Array.prototype, {
  concatAll() {
    let results = [];
    this.forEach(subArr => {
      subArr.forEach(item => {
        results.push(item);
      });
    });
    return results;
  }
});

然后你可以使用这样的代码:

let arr = [
  [1, 2, 3],
  [4, 5, 6]
];
console.log(arr.concatAll()); // -> [1, 2, 3, 4, 5, 6]

你也可以添加多种方法,比如:

Object.assign(Array.prototype, {
  sum() {
    return this.reduce((a, b) => a + b);
  },
  max() {
    return this.reduce((a, b) => (a > b) ? a : b);
  },
  min() {
    return this.reduce((a, b) => (a < b) ? a : b);
  }
});
let arr = [1, 2, 3];
console.log(arr.sum()); // -> 6
console.log(arr.max()); // -> 3
console.log(arr.min()); // -> 1

this的箭头函数的作用域是它的父作用域。因此,在这种情况下,this是未定义的。所以在这种情况下,你仍然需要一个函数。

检查的启动https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

与函数表达式相比,箭头函数表达式(也称为胖箭头函数)的语法更短,并且在词汇上绑定this值(不绑定自己的this、arguments、super或new.target)。箭头函数始终是匿名的。

ES6仍然可以通过使用for of:来简化代码

Array.prototype.concatAll = function(){
  let results = []
  for(let subArray of this)
    for(let item of subArray)
      results.push(item)
  return results
}

相关内容

最新更新