我很难理解实例属性的含义
例如在 Firefox ES6 类文档中它说 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
实例属性
实例属性必须在类方法内部定义
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
我只是将其视为具有构造函数的类,那么实例属性是什么意思?
最佳答案
实例属性有height
和width
:
class Rectangle {
constructor(height, width) {
this.height = height;
// -----^^^^^^
this.width = width;
// -----^^^^^
}
}
“实例”是一个对象。人们倾向于将“实例”与使用类类语法的代码相关联,但它仅表示对象(尽管通常暗示是“特定类的对象”)。
与“静态”或“类”属性对比:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
Rectangle.FOUR_BY_FOUR = new Rectangle(4,4);
那里,FOUR_BY_FOUR
是一个“类/静态”属性。或者使用 static class features proposal 提出的语法(目前第 3 阶段):
class Rectangle {
static FOUR_BY_FOUR = new Rectangle(4,4);
constructor(height, width) {
this.height = height;
this.width = width;
}
}
关于javascript - Javascript 中的实例是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50988049/