2010-05-01 150 views
1
function FakeClass(){}; 
FakeClass.prototype.someMethod = function(){}; 
FakeClass.prototype.otherMethod = function(){ 
    //need to call someMethod() here. 
} 

我需要从otherMethod调用someMethod,但显然它不起作用。如果我将它构建为单个函数(不是原型),我可以调用它,但调用prototyped不起作用。我怎么能这样做,就好像我正在像一个类的方法对待函数?如何从原型“类”中调用原型函数?

更新: 我打电话的方法触发一个jQuery事件之后。它会影响整个事物的行为方式吗?

function CicloviarioEngine(){}; 

CicloviarioEngine.prototype.test = function(){ 
    alert("Hey"); 
} 
CicloviarioEngine.prototype.initialize = function(){ 
    $('#add-route').click(function(){ 
    this.test(); //doesn't work 
    CicloviarioEngine.test(); //doesn't work 
    externalTest(); //works 

    }); 
} 

function externalTest(){ 
    alert("externalTest()"); 
} 

回答

4

this里面的事件处理函数和this里面的函数不一样(实际上它会是被点击元素的引用)。对付这种最简单的方法是到this值保存到一个变量,它的事件处理程序将其封闭的范围访问:

CicloviarioEngine.prototype.initialize = function() { 
    var that = this; 
    $('#add-route').click(function(){ 
     that.test(); 
    }); 
}; 
+1

工作正常。谢谢!并且谢谢@CMS。 – 2010-05-01 23:30:24

2

原型的成员将可以在对象实例,所以你可以使用关键字this简单地调用方法:

FakeClass.prototype.otherMethod = function(){ 
    this.someMethod(); 
}; 

检查为例here

+0

我更新的问题......我忘了说了jQuery部分,对不起。 :) – 2010-05-01 22:34:42