问题描述
我喜欢在Javascript中学习Class Property和Prototype之间的区别我的意思是在代码中显示:
I like to learn the difference between Class Property and Prototype in Javascript what I mean is shown in the code :
function Rectangle(x, y) {
this.width = x;
this.height = y;
}
Rectangle.UNIT = new Rectangle(1, 1);
Rectangle.prototype.UNIT = new Rectangle(1, 1);
我知道的原型是继承对象,这意味着UNIT将显示来自的所有实例现在但 Rectangle.UNIT = new Rectangle(1,1);
代码不做同样的事情?
The thing I know is prototype is working like inherit object which means UNIT will be shown all the instances from now on but Rectangle.UNIT = new Rectangle(1, 1);
code doesn't do the same thing ?
推荐答案
Rectangle.UNIT
是一个静态类属性。它只能在Rectangle类对象上访问。在任何Rectangle实例上都无法访问它。
Rectangle.UNIT
is a static class property. It can only ever be accessed on the Rectangle class object. It won't be accessible on any instances of Rectangle.
Rectangle.prototype.UNIT
是一个原型属性,可以在Rectangle实例上访问。
Rectangle.prototype.UNIT
is a prototype property and can be accessed on instances of Rectangle.
如果你创建一个继承自 Square >矩形,任何 Square
的实例将共享相同的原型属性,但不是任何静态类属性。
If you make a class Square
that inherits from Rectangle
, any instances of Square
will share the same prototype property, but not any static class properties.
你可能会发现这些文章很有用(虽然可能有点模糊):
You may find these articles helpful (though maybe a little obscure):
- http://phrogz.net/JS/Classes/OOPinJS.html
- http://phrogz.net/JS/Classes/OOPinJS2.html
- http://javascript.crockford.com/prototypal.html
这篇关于Javascript中类属性与函数原型的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!