为什么这个 prototypjs observe 对回调函数有绑定?
Why does this prototypjs observe have a bind on the callback function?
我运行在一个项目中加入了这个模式。
$('some_form').observe('keypress', (function(event) {
if (event.keyCode == Event.KEY_RETURN) {
this.some_function()
event.stop();
}
}).bind(this));
我想知道为什么handler上有.bind(this)
。如果有帮助,这些都在 Class.create() 的初始化函数中。
我问这个也是为了将其转换为 jQuery.
如果没有绑定,范围 (this
) 将是 some_form
元素。由于 some_function
不是表单元素的成员,您将无法调用它。
通过绑定,范围是包含范围,它可以访问 some_function
。
这是另一个解决范围问题的模式,它甚至与超级古老的浏览器兼容。
var _this = this;
$('some_form').observe('keypress', (function(event) {
_this.some_function();
}));
我运行在一个项目中加入了这个模式。
$('some_form').observe('keypress', (function(event) {
if (event.keyCode == Event.KEY_RETURN) {
this.some_function()
event.stop();
}
}).bind(this));
我想知道为什么handler上有.bind(this)
。如果有帮助,这些都在 Class.create() 的初始化函数中。
我问这个也是为了将其转换为 jQuery.
如果没有绑定,范围 (this
) 将是 some_form
元素。由于 some_function
不是表单元素的成员,您将无法调用它。
通过绑定,范围是包含范围,它可以访问 some_function
。
这是另一个解决范围问题的模式,它甚至与超级古老的浏览器兼容。
var _this = this;
$('some_form').observe('keypress', (function(event) {
_this.some_function();
}));