我遇到道格拉斯康乐福的Object.create方法,我希望有人也许能够解释一个特点:如果我创建一个对象的JavaScript的Object.create - 继承嵌套属性
- 说“人' - 使用对象字面符号,然后使用Object.create创建一个新对象 - 比如'anotherPerson' - 它继承了最初的'person'对象的方法和属性。
如果我然后更改第二个对象的名称值 - 'anotherPerson' - 它也会更改初始'person'对象的名称值。
这只是发生在属性嵌套,这段代码应该给你什么,我的意思是一个想法:
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'
如果我存储的名称值,而不嵌套那么这种奇怪的行为不会发生 - - 例如
// 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'
当使用具有构造函数和'new'关键字的古典风格的继承时,似乎不会出现这种嵌套问题。
如果有人能够解释为什么会发生这种情况,我会非常感激!
可能的重复:[克罗克福德的原型继承 - 嵌套对象的问题](http://stackoverflow.com/q/10131052/1048572) – Bergi 2014-06-08 12:59:55