Me he encontrado con una peculiaridad con el método de Douglas Crockfords Object.create la que estoy esperando que alguien podría ser capaz de explicar:JavaScript Object.create - heredar propiedades anidadas
Si creo un objeto - por ejemplo ' persona '- usando la notación literal del objeto, luego use Object.create para crear un nuevo objeto, digamos' anotherPerson ', que hereda los métodos y propiedades del objeto' persona 'inicial.
Si cambio los valores del nombre del segundo objeto - 'otra persona' - también cambia el valor del nombre del objeto 'persona' inicial.
Esto sólo ocurre cuando las propiedades están anidados, este código debe darle una idea de lo que quiero decir:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
};
// initiate new 'person' object
var person = {
name: {
first: 'Ricky',
last: 'Gervais'
},
talk: function() {
console.log('my name is ' + this.name.first + ' ' + this.name.last);
}
}
// create anotherPerson from person.prototype
var anotherPerson = Object.create(person);
// change name of anotherPerson
anotherPerson.name.first = 'Stephen';
anotherPerson.name.last = 'Merchant';
// call talk method of both 'person' and 'anotherPerson' objects
person.talk(); // oddly enough, prints 'Stephen Merchant'
anotherPerson.talk(); // prints 'Stephen Merchant'
Si tuviera que almacenar los valores de nombre y sin anidación entonces este extraño comportamiento no se produce - - p.ej
// initiate new 'person' object
var person = {
firstName: 'Ricky',
lastName: 'Gervais',
talk: function() {
console.log('my name is ' + this.firstName + ' ' + this.lastName);
}
}
// create anotherPerson from person.prototype
var anotherPerson = Object.create(person);
// change name of anotherPerson
anotherPerson.firstName = 'Stephen';
anotherPerson.lastName = 'Merchant';
// call talk method of both 'person' and 'anotherPerson' objects
person.talk(); // prints 'Ricky Gervais'
anotherPerson.talk(); // prints 'Stephen Merchant'
Este problema anidación no parece ocurrir cuando se utiliza un estilo clásico de la herencia con una función constructora y la palabra clave 'nuevo'.
Estaría muy agradecido si alguien puede explicar por qué ocurre esto?
posible duplicar: [herencia de Prototypal de Crockford - Problemas con objetos anidados] (http://stackoverflow.com/q/10131052/1048572) – Bergi