作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这是我的代码示例:
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
将成为窗口对象,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
}
};
关于javascript - 如何在 jQuery 中创建适当的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1336778/
这段代码在 Java 中的等价物是什么?我放了一部分,我对 I/O 部分感兴趣: int fd = open(FILE_NAME, O_WRONLY); int ret = 0; if (fd =
我正在尝试将维度为 d1,d2,d3 的张量 M[a1,a2,a3] reshape 为维度为 d2, d1*d3 的矩阵 M[a2,a1*a3]。我试过 M.reshape(d2,d1*d3) 但是
我是一名优秀的程序员,十分优秀!