Javascript 如何在jQuery中创建适当的闭包?
这是我的代码示例:Javascript 如何在jQuery中创建适当的闭包?,javascript,jquery,closures,Javascript,Jquery,Closures,这是我的代码示例: 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); } } 显然,单击我的输入会在控制台中显示输入。如何将bar改为
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);
}
}
显然,单击我的输入会在控制台中显示
输入。如何将bar
改为this
?这是因为当您创建事件时,会使用触发事件的DOM元素的上下文调用事件处理程序函数,this
关键字表示DOM元素
为了获得“条”,您应该存储对外部闭合的引用:
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
}
};
注意:如果在没有运算符的情况下调用条形函数,此
将成为窗口对象,baz
和foo
将成为全局变量,请小心
但是,我认为您的代码可以简化:
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
}
};
要在foo中获得bar,请执行以下操作:
bar = function() {
var me = this;
this.baz = function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change", this.foo);
}
this.foo = function(event){
// me, would be your bar object.
console.log(me);
}
}
给你,这是一个如何得到“这个”的例子
var bar=函数(){
this.baz=函数(){
this.input=$('.input');
this.input.bind(“keydown-keyup-focus-blur-change”,this.foo);
}
this.foo=函数(事件){
console.log(this);
}
}
点击
之所以会发生这种情况,是因为函数baz是通过bar.SO的实例调用的,所以bar是在“new bar()”上下文中执行的,而不是在窗口对象中执行的
如果您使用的是firebug(看起来是这样),您可以在单击控制台选项卡中的单击之前和之后在输入文本控件中键入时跟踪日志记录。在JavaScript中将实例方法用作回调时,这是一个常见问题。我使用此函数创建一个闭包来调用绑定到正确实例的方法:
function bound_method(instance, method) {
return function() {
return method.apply(instance, arguments);
};
}
然后,您可以将其用作回调来代替this.foo:
bound_method(this, this.foo)
与其他一些方案不同,这允许您将方法放在原型上,而不是在构造函数中创建它们。这样,您就只有一个实现的共享副本,而不是为bar的每个新实例重新创建这些函数
var bar = function() {};
$.extend(bar, {
baz: function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change",
bound_method(this, this.foo));
},
foo: function(event) {
console.log(this);
}
});
我想补充一点,您实际上并不需要“var bar=”部分。要内联调用闭包,请在最后一个分号之前添加“()”。是的,但还要注意,如果闭包是自动执行的,baz
和foo
将成为全局闭包,因为this
将是窗口对象。谢谢,我想我将使用这个“外部闭包”选项。但是我希望在input.bind()中有一个更优雅的,不知道的第二个绑定。我有一种感觉,我在某处见过类似的东西。还有其他选择吗?您的绑定方法()看起来很像bind(),对吗?是的,它与原型中的Function.bind或更新的ECMAScript标准非常相似。我曾考虑将其添加到函数原型中,但我们一直避免修改内置对象原型。
var bar = function() {};
$.extend(bar, {
baz: function() {
this.input = $('.input');
this.input.bind("keydown keyup focus blur change",
bound_method(this, this.foo));
},
foo: function(event) {
console.log(this);
}
});