JavaScript Uncaught TypeError: Cannot convert undefined or null to object
JavaScript Uncaught TypeError: Cannot convert undefined or null to object
我有一个问题,
// 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
绑定,
// 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
的调用上下文调用的,而不是 stack.push
作为回调传递的. (当作为回调传递时,调用上下文会丢失,除非您绑定函数,这是您在第三种方法中所做的)。
再举个例子:
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();
我有一个问题,
// 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
绑定,
// 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
的调用上下文调用的,而不是 stack.push
作为回调传递的. (当作为回调传递时,调用上下文会丢失,除非您绑定函数,这是您在第三种方法中所做的)。
再举个例子:
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();