访问Javascript原型函数

Accessing a Javascript prototype function

本文关键字:函数 原型 Javascript 访问      更新时间:2023-09-26

我有一个原型函数,比如event。

原型

Func("input_element_id").event("keyup",function(){
    alert("Works on keyup in an Input!");
}
Func.prototype= {
    keyup: function(func){
         //adding event listener and callback using func
    },
    event: function(e,func) {
         //what to do here to call function "keyup"
    }
};

原型名称在变量e中。但是,如何使用变量名来调用function呢?

我这样做是为了传递"keyup-keydown"将添加keyup和keydown监听器,这比单独调用每个原型函数要好。

谢谢。

var Func = function(element){
  this.element = element;
};
Func.prototype = {
    keyup: function(handler){
      this.element.onkeyup = handler;
    },
    event: function(e,handler){
        switch(e){
            case 'keyup':
              return this.keyup(handler);
            break;
        }
    }
}

http://jsfiddle.net/YDekw/

使用this访问接收对象。

this.keyup(func);

假设一个不错的浏览器或ES5垫片,看起来你想这样做:

e.split(" ").forEach(function(f) {
    this[f](func);
}, this);

请注意,它只是与点运算符一起使用的任何对象,也可以是任何对象。例如:

var f = new Func("input_element_id");
window.event = f.event;
window.event(); // this is window

best way实现这一点的方法是:

events: function(events,func) {
            this[events](func);
        }
    }

感谢CrazyTrain,正如他在Comments中提到的。