在以下JavaScript代码中,从function(elem) {...
内部,我如何引用reachMe
函数?我只是想将一个监听器附加到elem
,以便在reachMe
被点击时调用elem
。
如果我将whatHereToMeanTheReachMeFunction
替换为this
,则它不起作用,因为this
是window
对象。如果我把reachMe
放在那里我得到错误 Uncaught TypeError:无法读取属性' bindAsEventListener'未定义的。
var MyClass = Class.create();
MyClass.prototype = {
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
elem.observe('click', whatHereToMeanTheReachMeFunction.bindAsEventListener(this));
}
);
},
reachMe : function(event) {
console.log("Here I am.");
}
}
答案 0 :(得分:2)
我对你的代码做了一些调整,希望这会帮助你
var MyClass = Class.create({
//The class can be defined in one fell swoop
initialize : function(spec) {
$$('*[id^=prefix]').each(
function(elem) {
//you should only need normal bind() here
elem.observe('click',this.reachMe.bind(this));
},this
//include 'this' here to set the context inside the each method
);
//you could also do the above action like this, 1 observer vs multiple
document.on('click','*[id^=prefix]',this.reachMe.bind(this));
},
reachMe : function(event) {
console.log("Here I am.");
}
}