gpt4 book ai didi

javascript - 从 'initialize' 中的函数引用 Prototype.js 函数

转载 作者:行者123 更新时间:2023-11-30 16:33:57 26 4
gpt4 key购买 nike

在下面的 JavaScript 代码中,如何从 function(elem) {... 中引用 reachMe 函数?我只是想将一个监听器附加到 elem,以便在点击 elem 时调用 reachMe

如果我将 whatHereToMeanTheReachMeFunction 替换为 this 它不起作用,因为 thiswindow 对象。相反,如果我将 reachMe 放在那里,我会得到错误 Uncaught TypeError: Cannot read property 'bindAsEventListener' of undefined

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.");
}

}

最佳答案

我对您的代码做了一些调整,希望这对您有所帮助

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.");
}

}

关于javascript - 从 'initialize' 中的函数引用 Prototype.js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com