JS以self为参数创建自定义对象

JS create custom object with self as parameter

我想在最后将 "myEvent" 传递到 "myFunction",但在对象 "Event" 中,"myEvent" 未定义。

var myEvent = new Event(window,"click",myFunction,myEvent);

Event = function(target,type,func,parameter){
    console.log(parameter)                         //undefined
    var eventFunction = function(){
        func(parameter)
    }
    this.delete = function(){
        target.removeEventListener(type,eventFunction)
    }
    target.addEventListener(type,eventFunction);
}
myFunction(parameter){
    console.log(parameter);                  // says undefined but I want the object "myEvent"
}

抱歉英语不好

在构造函数根级别内使用 var that = this,然后在 eventFunction 内使用 func(that)。无需显式传递对新创建对象的引用,它已经存在于您的构造函数中。

如果您需要明确传递 myEvent 引用,请执行:

var wrapper = {myEvent: {}};
wrapper.myEvent = new Event(...,wrapper.myEvent);