首页 > 解决方案 > Javascript中的实例是什么意思

问题描述

我很难理解实例属性的含义

例如在 Firefox ES6 Class 文档中它说 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

实例属性

实例属性必须在类方法中定义

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

我只是将其视为具有构造函数的类,那么实例属性是什么意思?

标签: javascript

解决方案


实例属性有heightwidth

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一个“类/静态”属性。或者使用静态类特性提案(目前是第 3 阶段)提出的语法:

class Rectangle {
  static FOUR_BY_FOUR = new Rectangle(4,4);

  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

推荐阅读