2014-01-23 63 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()