【问题标题】:What is difference between method attached to prototype or object instance in Javascript?Javascript中附加到原型或对象实例的方法有什么区别?
【发布时间】: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) 在类上编写方法?

【问题讨论】:

标签: javascript oop constructor


【解决方案1】:

原型最好以不同的方式显示。

function rectangle(w, h) {
    var rect = {};
    rect.width=w; 
    rect.height=h; 
    rect.area=function() { return this.width * this.height; };
    return rect;
}

var Rectangle = {
    area: function() { return this.width * this.height; }
}

function rectangle(w, h) {
    var rect = Object.create(Rectangle);
    rect.width=w; 
    rect.height=h; 
    return rect;
}

这个想法很简单,你把通用的东西放在一个原型对象上,然后你从它继承。

至于你想什么时候使用原型?总是。

当然你可能想Improve ES5 OO with sugar

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 2011-02-22
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2017-05-12
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多