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

JS create custom object with self as parameter

本文关键字:创建 自定义 对象 参数 self JS      更新时间:2023-09-26

我想把"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);