在下面的JavaScript代码中,如何从function(elem) {...内部引用reachMe函数?我只是试图将侦听器附加到elem,以便在单击reachMe时调用elem

如果我将whatHereToMeanTheReachMeFunction替换为this,它将不起作用,因为thiswindow对象。相反,如果我放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.");
    }

}

最佳答案

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

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

}

10-06 07:33