![](/img/trans.png)
[英]Proper pattern to define methods of properties in a javascript “class”
[英]Proper way to define properties in a Javascript contructor
因此,我是javascript新手(来自强大的Java背景),我想知道在类或构造函数中定义属性或变量的正确方法。
function RootNode(sTitle, authName, storyNum){
this.sTitle = sTitle;
this.authName = authName;
this.storyNum = storyNum;
this.creationDate = new Date();
}
要么
function RootNode(sTitle, authName, storyNum){
var sTitle = sTitle;
var authName = authName;
var storyNum = storyNum;
var creationDate = new Date();
}
简单答案:使用第一个
更详细的答案
第一个代码段在对象上设置sTitle
, authName
, storyNum
和creationDate
属性。
第二个片段创建4个局部变量并设置其值。 这些变量无法从函数外部访问。
您可以像下面这样一起使用局部变量和对象变量:
function RootNode(sTitle, authName, storyNum) {
this.sTitle = sTitle; // you can access this variable when you . into the object
var privateVariable = 'You cannot see this variable when you . into the object directly';
this.methodInObject = function() {
return privateVariable; // but you can access the variable from the function
}
}
注意: 您可能想添加一个return this;
在构造函数的末尾,以便它返回您构造的对象。
更新:每评论,你不必 return this;
因为使用new RootNode
会自动进行(自动使用+1?)
进一步阅读
您可以使用第一种样式,但我个人更喜欢这种样式: http : //www.w3schools.com/js/js_objects.asp
第一种方法是正确的。
function RootNode(sTitle, authName, storyNum) {
this.sTitle = sTitle;
this.authName = authName;
this.storyNum = storyNum;
this.creationDate = new Date();
}
但是,此方法实际上并不像类,它更像是一个唯一的对象。 用这种方式定义对象更像是Java类。
function RootNode(sTitle, authName, storyNum) {
//your constructor
this.sTitle = sTitle;
this.authName = authName;
this.storyNum = storyNum;
this.creationDate = new Date();
}
RootNode.prototype.myMethod = function() {
//my code
}
该模式很有用,因为它允许多个实例化而无需为属性复制内存。 另外,如果要创建子类,则很有必要。 阅读本文以了解原型和构造函数属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.