What is difference between method attached to prot

2019-04-17 10:51发布

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?

1条回答
萌系小妹纸
2楼-- · 2019-04-17 11:52

prototypes are best shown differently.

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

vs

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;
}

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

查看更多
登录 后发表回答