gpt4 book ai didi

Javascript函数指针指向对象函数错误抛出错误: TypeError: can't convert undefined to object

转载 作者:行者123 更新时间:2023-11-30 23:58:42 25 4
gpt4 key购买 nike

我目前正在开始阅读 JavaScript,我想知道为什么以下代码会抛出错误:

a = [0,1,2,3];
x = a.pop;
x();

(抛出错误:TypeError:无法将 undefined 转换为对象)。

虽然下面的代码工作得很好:

x = console.log
x("hello");

这两者有什么区别?有什么方法可以在变量中存储对 a.pop 的可调用引用吗?

最佳答案

@Teemu 所说的没有什么可补充的,他回答得更快,但这里有一个片段,您可以在其中扩展他的评论,以下片段使用 call函数添加应应用 .pop() 的上下文,也可以使用 .apply()

let a = [0,1,2,3];
const x = a.pop;

x.call(a);
console.log(a);

x.apply(a);
console.log(a);

关于Javascript函数指针指向对象函数错误抛出错误: TypeError: can't convert undefined to object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60889434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com