在我的代码中向原型添加属性的正确方法

时间:2016-06-02 00:34:52

标签: javascript properties prototype

嘿我试图添加'事件'和回调函数" fun"到MyEvents的原型并且不理解下面代码的一部分!

function MyEvents(events){
this.events={};
}

MyEvents.prototype.adding=function(event,func){
var array=[]
this.array.push(func);
this.array.push(event);
this.events[event] = array; //I don't understand this part-why is that necessary?
}

有人可以解释一下吗? 谢谢!!

1 个答案:

答案 0 :(得分:0)

你最有可能尝试这样做:

//constructor function
function MyEvents(){
    this.events={};
}
//extending the prototype with a function called adding  
MyEvents.prototype.adding = function(event,func){
    this.events[event] = func
}
//instantiating a new object using the new operator on the constructor function
my_new_obj = new MyEvents()
//calling the adding function on the prototype and passing it the two arguments
my_new_obj.adding('test',function greet(){console.log('Hello')})
//calling the function you just added
my_new_obj['events']['test']()

另外,请注意,这可能非常强大,因为您添加到原型的方法(函数)可以访问实例化的my_new_obj属性。

相关问题