JavaScript 未捕获类型错误 : Cannot convert undefined or null to object

标签 javascript foreach this bind

我有一个问题,

// case 1
const stack = [];
[1,2,3].forEach(stack.push);

这会抛出错误

Uncaught TypeError: Cannot convert undefined or null to object
    at push (<anonymous>)
    at Array.forEach (<anonymous>)
    at <anonymous>:1:9

但是这样就好了,

// case 2
const stack = [];
[1,2,3].forEach(element => stack.push(element));
console.log(stack); // [1,2,3]

如果您用 this 引用自身来绑定(bind)堆栈,

// case 3
const stack = [];
[1,2,3].forEach(stack.push.bind(stack));
console.log(stack); // (9) [1, 0, Array(3), 2, 1, Array(3), 3, 2, Array(3)]

它也以另一种方式起作用。

这些怎么会发生呢?方法(情况 1)和箭头函数(情况 2)有什么区别?

最佳答案

stack.push引用Array.prototype.push。这:

const stack = [];
[1,2,3].forEach(stack.push);

不起作用,因为它相当于:

const stack = [];
[1,2,3].forEach(Array.prototype.push);

const callback = Array.prototype.push;
callback(1, 0, [1, 2, 3]);
callback(2, 1, [1, 2, 3]);
callback(3, 2, [1, 2, 3]);

这不起作用,因为没有要推送到的数组的 this 上下文。

方法 2 有效,因为您正在执行 => stack.push(element) - .push 正在使用 stack 的调用上下文进行调用code>,而不是作为回调传递的 stack.push。 (当作为回调传递时,除非您绑定(bind)该函数,否则调用上下文将丢失,这在第三个方法中执行)。

再举一个例子:

const obj = {
  fn() {
    console.log('fn. this is:', this);
  }
};

const callback = obj.fn;
// this does not refer to the object now:
callback();

// but this will:
obj.fn();

关于JavaScript 未捕获类型错误 : Cannot convert undefined or null to object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67830878/

相关文章:

javascript - 在文本输入框中添加 block ,类似于电子邮件应用程序到字段

javascript - _.each(list, iterator, [context]) 中的上下文是什么?

Javascript OOP : binding method to event handler

php - 警告 : Invalid argument supplied for foreach()

javascript - 在全局上下文中使用类方法时, `this` 为未定义

javascript - 在php中设置后台计时器

javascript - Daterangepicker 无法在网页 ASP.NET MVC 中工作

javascript - HTML5游戏代码中的跳跃角色

php - 如何在循环中的变量上应用 jQuery 中的 css?

php - PDO - 对多个 foreach 循环使用相同的查询