2014-05-06 32 views
0

我想与PhoneGap一起使用OO,我注意到我不能在他自己的方法中使用“this”对象的引用。Phonegap Javascript OO,这个参考

例:

var App = function() { 
    this.a = function() { 
     return true; 
    } 

    this.b = function() { 
     alert(this.a()); 
    } 
} 

在App.b()当我在浏览器上运行它正常工作,但作为一个PhoneGap的应用(Android)没有。有谁知道为什么?

我解决了这个有:

var App = function() { 
    var self = this; 

    this.a = function() { 
     return true; 
    } 

    this.b = function() { 
     alert(self.a()); 
    } 
} 

,并调用它

var app = new App(); 
app.b(); 

但是看起来不是一个好的做法。

谢谢。

+0

什么是应该为你在'App.b()'中成为'this'?你不是错过了一个'新'吗? –

+0

是的,我打电话像,var app = new App(),然后app.b()。问题是,这在浏览器上正常工作,但作为一个Android应用程序进行测试时,它什么都不做。 –

+1

您在问题中显示的代码与您的评论非常不同。 –

回答

0

也许你正在寻找的代码是:

var App = { 
    a: function() { 
     return true; 
    }, 
    b: function() { 
     alert(this.a); 
    } 
} 

编辑

如果你想实例化,那么这样做:

function App() {} 
App.prototype = { 
    a: function() { 
     return true; 
    }, 
    b: function() { 
     alert(this.a); 
    } 
} 
var app1 = new App(), 
    app2 = new App() 

app2.a() // true 
+0

我正在尝试将它用作一个类。不幸的是,这样我就不能实例化多个App对象。 –