无法在JavaScript类中设置属性

时间:2018-09-04 06:06:20

标签: javascript constructor properties

我只是在JavaScript的类中设置属性:

class BookingReports extends ReportsInterface{ 
    var categoryID;
    constructor() {
        super();
    }

    init(CatID)
    {
        this.categoryID=CatID;            
    }
}

但是JavaScript根本不接受变量,并给出错误“意外标识符”。

enter image description here

我不知道什么是语法错误。是因为继承还是super关键字?我什至尝试对整个声明使用绑定。但这不起作用。

1 个答案:

答案 0 :(得分:1)

var categoryID在那里不合适。您不会在class级别声明变量;您可以在构造函数或方法中声明变量。

在您的情况下,您可能根本不想声明一个变量。而是在构造函数中创建属性:

class BookingReports extends ReportsInterface{ 
    constructor() {
        super();
        this.categoryID = /*...some default value...*/;
    }

    init(CatID)
    {
        this.categoryID=CatID;            
    }
}

侧面说明:使用init方法没有多大意义;这就是构造函数的用途。所以:

class BookingReports extends ReportsInterface { 
    constructor(catID) {
        super();
        this.categoryID = catID;
    }
}

在某个时候,class fields proposal将进入阶段4,届时,您可以在class级别“声明”属性,

// Valid if/when the class fields proposal advances
class BookingReports extends ReportsInterface { 
    categoryID; // Declares the property
    constructor(catID) {
        super();
        this.categoryID = catID;
    }
}

如果要在构造函数中初始化属性,则没有太多意义;但这对于预先告知读者(和JavaScript引擎)对象的标准“形状”很有用,而不是让它们(及其)分析构造函数的代码。

相关问题