簡體   English   中英

JavaScript 未捕獲類型錯誤:無法將未定義或 null 轉換為 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作為回調傳遞的。 (當作為回調傳遞時,調用上下文會丟失,除非您在第三種方法中綁定 function)。

再舉一個例子:

 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM