Javascript中的实例是什么意思
我很难理解实例属性的含义 例如,在FirefoxES6类文档中 实例属性 实例属性必须在类方法内部定义Javascript中的实例是什么意思,javascript,Javascript,我很难理解实例属性的含义 例如,在FirefoxES6类文档中 实例属性 实例属性必须在类方法内部定义 class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } 我只是把它看作是一个带有构造函数的类,那么实例属性是什么意思呢?那里的实例属性有高度和宽度: class Rectangle { constructor(height,
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = 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\u BY\u FOUR
是一个“类/静态”属性。或者使用(当前阶段3)提出的语法:
这意味着矩形
的每个实例都具有高度
和宽度
属性
稍后,它们将演示如何创建实例
const square = new Rectangle(10, 10);
这里,square
是矩形的一个实例,其高度和宽度属性都初始化为10。您可以将类
描绘为蓝图或建模。使用您在问题中定义的类进行解释
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
我们有一个名为Rectangle
的类作为“蓝图”或设计。现在,我们可以根据这个“蓝图”/矩形
let bigRectangle = new Rectangle(300,300);
let smallRectangle = new Rectangle(50,50);
你知道什么是“实例”吗这些属性对于您创建的类的每个实例都是独立的。当您有一个类person
,那么您希望该类的name
属性为您创建的每个person实例保存一个不同的值……与此相反的是一个静态属性,所有实例共享一个。
let bigRectangle = new Rectangle(300,300);
let smallRectangle = new Rectangle(50,50);