这里: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。但是,这只是有时,而不是所有的时间,我不明白为什么以及何时发生。
有什么建议吗?为什么会发生?
如果您将该“prepareForm”函数作为事件处理函数传递,它将失去与该对象的关系。 – Pointy
'this.validate(){'看起来不正确?你的意思是'this.validate = function(){'? –
另请注意,该博客文章*真的*由JavaScript最佳实践标准。 – Pointy