gpt4 book ai didi

Javascript:通过onclick调用时对象中的函数未定义

转载 作者:行者123 更新时间:2023-11-29 10:20:03 25 4
gpt4 key购买 nike

我在这里尝试一些代码,

var cat={
col:"Red",
getCol:function(){
document.writeln(this.col);
}
}

function getCol(){
document.writeln(cat.col);
}

$(function(){
$("#button1").click(cat.getCol);
$("#button2").click(getCol);
})

但是按钮 1 得到了 undefined,按钮 2 得到了“红色”。谁能告诉我为什么?

如果我将它更改为 $("#button1").click(cat.getCol());,我得到了我需要的“红色”...

最佳答案

首先

$("#button1").click(cat.getCol);

给你 undefined 因为 cat.getCol 的主体使用 this 而不是 cat 当这个事情运行。我建议在这里使用 Function.prototype.bind,或者如果您担心跨浏览器的兼容性,可以使用其他几个变体。对于将“方法”设置为事件处理程序并确保 this 保持绑定(bind)到封闭对象的问题,有许多已发布的解决方案。

下一步

$("#button2").click(getCol);

工作正常,因为 getCol 直接使用 cat

最后

$("#button1").click(cat.getCol());

是非常错误的。表达式 cat.getCol() 是一个返回 undefined调用。这不是为点击处理程序设置的好值。您刚刚看到 document.write 发生,但不是响应点击。

附录

Live demo using bind

关于Javascript:通过onclick调用时对象中的函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13853711/

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