gpt4 book ai didi

javascript - 如何在 jQuery 中创建适当的闭包?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:38:37 25 4
gpt4 key购买 nike

这是我的代码示例:

var bar = function() {

this.baz = function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change", this.foo);
}

this.foo = function(event){
console.log(this);
}

}

显然,单击我的输入会在控制台中显示 input。我如何才能将 bar 改为 this

最佳答案

发生这种情况是因为当您 bind一个事件,使用触发事件的 DOM 元素的上下文调用事件处理函数,this 关键字表示 DOM 元素。

要获得“bar”,您应该存储对外部闭包的引用:

var bar = function() {
var self = this;

this.baz = function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change", this.foo);
}

this.foo = function(event){
console.log(this); // the input
console.log(self); // the bar scope
}
};

注意:如果调用 bar 函数时没有 new运算符,this 将成为窗口对象,bazfoo 将成为全局变量,小心!

但是我认为您的代码可以简化:

var bar = {
baz: function() {
var input = $('.input');
input.bind("keydown keyup focus blur change", this.foo);
},

foo: function(event){
console.log(this); // the input
console.log(bar); // reference to the bar object
}
};

关于javascript - 如何在 jQuery 中创建适当的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1336778/

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