2014-01-23 70 views
0

這裏:http://www.phpied.com/3-ways-to-define-a-javascript-class/描述了3種用javascript定義「class」的方法。我選擇在我的代碼使用第3方法:javascript「class」變量undefined

var apple = new function(){ 
    //code here 
} 

我用這種結構,以此來分開命名空間中的代碼,我的意思是我有更多的變量作爲蘋果在同一個js文件,而且每一個可能包含具有相同名稱的函數。現在

var customer = new function(){ 
    this.URL = "//customer/"; 
    this.json = {}; 
    this.getData = function(id){ 
     this.prepareForm(); 
     this.json = requestData(this.URL); //requestData deffined in another place 
    } 
    this.save = function(){ 
     //code 
    } 
    this.validate = function(){ 
     //code 
    } 
    this.prepareForm = function(){ 
     //code 
    } 
    // more code here 
} 


var employee = new function(){ 
    //code here, something like the customer code 
} 


var partner = new function(){ 
    //code here, something like the customer code 
} 

,我注意到,有時this.URL不確定。該函數存在,被定義並在上下文上運行,該變量不存在,我需要將其稱爲customer.URL。但是,這只是有時,而不是所有的時間,我不明白爲什麼以及何時發生。

有什麼建議嗎?爲什麼會發生?

+1

如果您將該「prepareForm」函數作爲事件處理函數傳遞,它將失去與該對象的關係。 – Pointy

+0

'this.validate(){'看起來不正確?你的意思是'this.validate = function(){'? –

+0

另請注意,該博客文章*真的*由JavaScript最佳實踐標準。 – Pointy

回答

0

this.jsonthis.josn = requestData(this.URL)是不同的。不可能是答案,但肯定不是同一個變量。看一看。

this.json = {}; 
this.getData = function(id){ 
    this.prepareForm(); 
    this.josn = requestData(this.URL); //requestData deffined in another place 
+0

爲什麼不呢?我不明白 –

+0

是拼寫錯誤看它一個是this.json和其他this.JOSN – ncubica

+0

只是一個拼寫錯誤,因爲我直接在瀏覽器窗口上寫所有的代碼。真正的代碼是正確的,有時候這個變量是未定義的 –

1

您在代碼中出現了一些語法錯誤,並且@Pointy指出,該文章非常老套。我真的覺得你必須改變你創建JavaScript類的方法,你最好使用原型來定義類的方法,這是,恕我直言,更好的方式做你想要的:

var Customer = function Customer(){ 
    this.URL = "//customer/"; 
    this.json = {}; 
}; 
Customer.prototype.getData = function(id){ 
    this.prepareForm(); 
    this.josn = requestData(this.URL); 
}; 
Customer.prototype.save = function()(){ 
    //code 
}; 
Customer.prototype.validate = function()(){ 
    //code 
}; 
Customer.prototype.prepareForm = function()(){ 
    //code 
}; 
var customer = new Customer(); 
//you can here call your methods like: 
customer.validate(); 
  • 以及您this.URL未定義的具體問題,只有當你調用不同的上下文,它甚至可以作爲回調或處理程序,基於您的代碼傳遞發生此問題我猜你是通過getData函數作爲回調如果是這樣的話,最好創建一個匿名函數並在其中調用customer.getData()