【发布时间】:2012-01-04 20:35:23
【问题描述】:
我对 Javascript 中原型的使用有点困惑。
我们来看下面的例子:
(1)
函数矩形(w,h){ 这个.宽度=w; 这个.height=h; this.area=function() { this.width * this.height; } }还有一个类似的情况,将区域附加到原型上,如下所示:
(2)
函数矩形(w,h){ 这个.宽度=w; 这个.height=h; } Rectangle.prototype.area=function() { this.width * this.height; }- (1)和(2)有什么区别?
- 您何时会使用 (1) 或 (2) 在类上编写方法?
【问题讨论】:
-
this.prototype不存在。 -
正确:一个有效,另一个无效:-)
标签: javascript oop constructor