1

我试图在输入按键检测事件处理程序中传递对象原型函数调用,但不知道如何去做。任何帮助将不胜感激代码如下:

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
}
4

2 回答 2

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(); 
    }
}​
于 2012-09-24T02:38:03.270 回答
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
  }
}
于 2012-09-24T02:33:04.657 回答