将对象原型函数调用传递给输入按键检测事件处理程序

时间:2012-09-24 02:30:21

标签: javascript javascript-events

我正在尝试在输入按键检测事件处理程序中传递对象原型函数调用,但我不确定如何解决此问题。任何帮助将不胜感激。代码如下:

function foo{};

foo.prototype.shout = function() {
  alert(shout);
}

foo.prototype.someOtherFunction = function (event) {
  var e = event || window.event,
      code = e.charCode || e.keyCode;

    if(code === 38) {
       foo.shout// This is what doesn't work - sorry for the confusion
    }
}

foo.prototype.applyKeypress = function (_input) {
  var self = this;
      _input.onkeypress = foo.someOtherFunction; // someOtherFunction applied here
}

2 个答案:

答案 0 :(得分:2)

如我在帖子前几秒所说 - 你没有创建对象

http://jsfiddle.net/Smzuu/2/

我稍微更改了你的代码,以便它可以运行。在编写这个示例代码时,你错过了一些小事,我希望

function foo(){};

foo.prototype.shout = function() {
  alert("hello"); //alert(shout); // shout was not defined.
}

var sampleInput = document.getElementById('sampleInputField');

sampleInput.onkeypress = function(e) {
    if(e.charCode === 97) { // A pressed
      new foo().shout(); 
    }
}​

答案 1 :(得分:1)

不,它不起作用,因为你还没有创建一个对象:

function foo(){};

foo.prototype.shout = function() {
  alert(shout);
}

var o = new foo();

var sampleInput = document.getElementById('sampleInputField');

sampleInput.onkeypress = function(e) {
  if(code === 38) { //up arrow press
    o.shout() //now it works because it's an object, not a constructor
  }
}