2010-08-11 16 views
11

Me lo chiedo circa la natura prototipale di JavaScript, ed i benefici di esso, e sono sceso al seguente elenco:I benefici di JavaScript Prototype

1) Eredità

cat.prototype = animal 

2) memoria efficienza

a.prototype.b = function() {} 

var a1 = new a(); 
var a2 = new a(); 

Poi a1.b e a2.b sono essenzialmente le stesse obiet t, dove:

var a = function() { 
      this.b = function() {}; 
     } 

var a1 = new a(); 
var a2 = new a(); 

a1.b e a2.b sarebbero diversi oggetti funzione e occuperebbero più memoria.

3) Aggiunta di metodi/campi a oggetti multipli, già creati, "out in the wild".

var a = function() {} 

var a1 = new a(); 
var a2 = new a(); 

a.prototype.b = function() {} 

a1.b(); 
a2.b(); 

Quindi la domanda è, sono questi corrette?

... e ci sono altri vantaggi che ho perso?

Cheers!

+0

ben motivata. è fondamentalmente la versione Javascript delle proprietà/metodi di classe vs. istanza –

risposta

6

Questi sono tutti corretti.

Naturalmente, ci sono "svantaggi" così:

Nessun chiusure

function a() { 
    var ival = 0; 
    this.start = function(){ ival = setInterval(function(){ }, 300); } 
    this.finish = function(){ clearTimeout(ival); } 
} 

confrontare a:

function a() { 
    this.ival = 0; 
} 
a.prototype.start = function(){ this.ival = setInterval(function(){ }, 300); } 
a.prototype.finish = function(){ clearTimeout(this.ival); } 
Problemi correlati