我想了解 Javascript 中类属性和原型(prototype)之间的区别,我的意思在代码中显示:
function Rectangle(x, y) {
this.width = x;
this.height = y;
}
Rectangle.UNIT = new Rectangle(1, 1);
Rectangle.prototype.UNIT = new Rectangle(1, 1);
我知道原型(prototype)的工作方式类似于继承对象,这意味着 UNIT 将从现在开始显示所有实例,但 Rectangle.UNIT = new Rectangle(1, 1);
代码不会做同样的事情?
最佳答案
Rectangle.UNIT
是一个static 类属性。它只能在 Rectangle 类对象上访问。它在 Rectangle 的任何实例上都不可访问。
Rectangle.prototype.UNIT
是一个原型(prototype)属性,可以在 Rectangle 的实例上访问。
如果您创建一个继承自 Rectangle
的类 Square
,Square
的所有实例将共享相同的原型(prototype)属性,但不是任何静态类属性。
您可能会发现这些文章很有帮助(尽管可能有点晦涩):
关于javascript - Javascript 中类属性和函数原型(prototype)的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1355561/