What is difference between method attached to prot

2019-04-17 10:59发布

问题:

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:

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