gpt4 book ai didi

javascript - this.show 和 this.show() 函数调用的区别?

转载 作者:行者123 更新时间:2023-11-30 07:40:32 27 4
gpt4 key购买 nike

$(document).ready(function(){       
$('html').addClass('js');
var contactForm = {
init: function(){
$('<button></button>',{
text: 'contact me'
}).appendTo('article')
**.on('click', this.show);**
},

show: function(){
console.log('show is clicked');
}
}

contactForm.init();
});

在 onClick 调用中,为什么 .on('click', this.show()); 在加载 dom 时立即执行,而稍后仅在单击按钮。

最佳答案

末尾的括号表示应立即调用前面的函数。如果没有方括号,它将成为函数的引用。

因此 on('click', this.show()); 将意味着 show 函数在 click 加载时被调用> 设置了处理程序,并将其返回值设置为事件处理程序。

其中 on('click', this.show); 为点击处理程序提供了对 show 函数的引用,该函数将在 点击事件发生。

最佳做法是将函数的引用传递给事件处理程序——即。后一个例子。

关于javascript - this.show 和 this.show() 函数调用的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299604/

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