这是我正在组合的原型(prototype)类的片段。范围界定解决方法对我来说有点老套,可以改进或以不同的方式完成吗?
var myClass = Class.create({
initialize: function() {
$('formid').getElements().each(function(el){
$(el).observe("blur", function(){
this.validateEl(el);
}.bind(this,el));
},this);
},
validateEl: function(el){
// validate $(el) in here...
}
});
另外,在我看来,我可以为事件观察者做这样的事情:
$('formid').getElements().invoke("observe","blur" ...
不确定如何传递元素引用?
最佳答案
你确实可以稍微简化一下:
var myClass = Class.create({
initialize: function() {
var self = this;
// To demo that we keep the instance reference, set a
// property on the instance
this.message = "Hi there";
$('formid').getElements().invoke("observe", "blur", blurHandler);
function blurHandler() {
// `self` references our instance
// `this` references the element we're observing
self.validateEl(this);
}
},
validateEl: function(el){
// validate $(el) in here...
// note that because of the way we called it, within this function,
// `this` references the instance, so for instance:
this.foo(); // alerts "Hi there!"
},
foo: function() {
alert(this.message);
}
});
它使用 invoke
(如您所建议的)和处理程序的命名函数(不必命名,但我发现让您的函数具有名称非常有帮助)。处理程序是一个闭包。在 initialize
函数中,我使用一个变量指向 this
,因为该变量随后可用于闭包。 (我将其称为 self
,因为这是为此原因使用别名 this
时的标准做法。)处理程序利用 Prototype 设置 this
的 native 功能在事件处理程序中到被观察的元素。当我们通过闭包的 self
引用调用 validateEl
时,我们按照正常方式将其作为成员函数调用,因此在 validateEl
中,this
指的是实例。
说到命名函数,您的 initialize
和 validateEl
函数都是匿名的,这意味着在调用堆栈等调试器中,您只会看到“(?) “而不是一个好听、方便的名字。我总是推荐实际的命名函数; more here .
关于javascript - 从原型(prototype)类改进此代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817730/