2011-05-13 13 views
7
var print = function(text){ 
    document.write(text); 
    document.write("</br>"); 
} 

var A = function(){ 
} 
A.prototype.name="A"; 

var B = function(){ 
} 
B.prototype = new A(); 
B.prototype.name="B"; 

var C = function(){ 
} 
C.prototype = new B(); 
C.prototype.name="C"; 

obj = new C(); 
print(obj.name); 
print(obj.constructor.prototype.name); 
print(obj.constructor == A); 

Este código da salida siguiente:Herencia de prototipo. obj-> C-> B-> A, pero obj.constructor es A. ¿Por qué?

C 
A 
true 

Por qué obj.constructor aquí es A y C no?

+0

La propiedad del constructor se define en el objeto prototipo, y cuando la asigne, se asignan todos sus miembros. Cualquier miembro que desee tener valores diferentes debe estar definido, o heredará el constructor, toString, valueOF y cualquier otra cosa que contenga el prototipo. – kennebec

+0

Gracias, me di cuenta de esto ya – nahab

Respuesta

7

Como se ve en this code sample, tiene que restablecer manualmente la propiedad .constructor al utilizar la herencia, o el constructor está siendo anulado cuando se llama a new A() o new B():

B.prototype = new A(); 
B.prototype.constructor = B; // need this line to fix constructor with inheritance 

Este es un ejemplo de trabajo: http://jsfiddle.net/93Msp/.

Espero que esto ayude!

+0

Interesante - alguna idea de por qué este es el comportamiento deseable? –

+1

Dado que OO en JavaScript es un gran truco, cosas como esta son de esperar. – mellamokb

+0

Sí. Esto ayuda) – nahab

4

Para realizar una imagen clara:

En la cadena única

obj->"new B()"->"new A()" // where obj is the same as "new C()" 

"new A()" objeto tiene propiedad constructor. Todos los demás objetos obtienen la propiedad constructor de la cadena del prototipo.

En el código:

var A = function(){ 
} 
A.prototype.name="A"; 
// A had not create "constructor" property for "new A()" 
// so, looking at the prototype 
// According to ECMAScript spec 13.2.10 
// A.prototype.constructor == A 
// thus 
// "new A()".constructor == A 

var B = function(){ 
} 
B.prototype = new A(); 
B.prototype.name="B"; 
// B had not create "constructor" property for "new B()" 
// looking at the prototype 
// B.prototype is "new A()" 
// as shown above 
// "new A()".constructor == A 
// thus 
// B.prototype.constructor == A 
// and at the end 
// "new B()".constructor == A 

var C = function(){ 
} 
C.prototype = new B(); 
C.prototype.name="C"; 
// C had not create "constructor" property for "new C()"/"obj" 
// looking at the prototype 
// C.prototype is "new B()" 
// looking up to "new B()".prototype 
// "new B()".prototype is "new A()" as shown above 
// "new A()".constructor == A 
// and finally 
// C.prototype.constructor == A 

obj = new C(); 
print(obj.name); 
print(obj.constructor.prototype.name); 
print(obj.constructor == A); 

Así como escribió mellamokb debemos sobreescribir (crear, si más precisa) constructor propiedad.

Cuestiones relacionadas