在Javascript构造函数中定义属性的正确方式

Proper way to define properties in a Javascript contructor

本文关键字:方式 属性 定义 Javascript 构造函数      更新时间:2023-09-26

所以我是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();  
}

简单答案:使用第一个


更详细的答案

第一个代码段设置对象的sTitleauthNamestoryNumcreationDate属性。

第二个片段创建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表示使用自动?:))


进一步阅读

  • MDN中的面向对象JavaScript简介
  • 伪古典模式
  • JavaScript继承:伪经典与原型

您可以使用第一种样式,但我个人更喜欢这样: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
}

这种模式非常有用,因为它允许多次实例化,而不会复制属性的内存。此外,如果您想要创建子类,这也是必要的。阅读本文以了解原型和构造函数属性