Javascript 中附加到原型或对象实例的方法有什么区别?
我对 Javascript 中原型的使用有点困惑。
让我们看下面的例子:
(1)
function Rectangle(w, h) { this.width=w; this.height=h; this.area=function() { this.width * this.height; } }
类似的情况,该区域附加到原型上,如下所示:
(2)
function Rectangle(w, h) { this.width=w; this.height=h; } Rectangle.prototype.area=function() { this.width * this.height; }
- (1) 和 (2) 之间有什么区别?
- 你什么时候会使用(1)或(2)在类上编写方法?
I am a bit confused about the usage of prototypes in Javascript.
Let's take the following example:
(1)
function Rectangle(w, h) { this.width=w; this.height=h; this.area=function() { this.width * this.height; } }
And a similar case where the area is attached to a prototype as follows:
(2)
function Rectangle(w, h) { this.width=w; this.height=h; } Rectangle.prototype.area=function() { this.width * this.height; }
- What is the diffrence between (1) and (2) ?
- When would you use (1) or (2) for writing methods on classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原型最好以不同的方式展示。
vs
这个想法很简单,你把常见的东西放在原型对象上,然后继承它。
至于什么时候要用原型?总是。
当然,您可能想要用 Sugar 改进 ES5 OO
prototypes are best shown differently.
vs
The idea is simple, you put common stuff on a prototype object and you then inherit from it.
As for when you want to use the prototype? Always.
Of course you probably want to Improve ES5 OO with sugar