Ric*_*ard 12 javascript inheritance object object-create
我遇到过Douglas Crockfords Object.create方法的特殊性,我希望有人可以解释一下:
如果我创建一个对象 - 比如'person' - 使用对象文字符号,那么使用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'
Run Code Online (Sandbox Code Playgroud)
如果我在没有嵌套的情况下存储名称值,则不会发生这种奇怪的行为 - 例如
// 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'
Run Code Online (Sandbox Code Playgroud)
当使用带有构造函数和'new'关键字的经典继承风格时,似乎不会出现此嵌套问题.
如果有人能够解释为什么会发生这种情况,我会非常感激!?
CMS*_*CMS 19
发生这种情况是因为它anotherPerson.name是一个对象,它存储在原始链的原始person对象的上方:
//...
var anotherPerson = Object.create(person);
anotherPerson.hasOwnProperty('name'); // false, the name is inherited
person.name === anotherPerson.name; // true, the same object reference
Run Code Online (Sandbox Code Playgroud)
您可以通过将新对象分配给name新创建的对象的属性来避免这种情况:
// create anotherPerson from person
var anotherPerson = Object.create(person);
anotherPerson.name = {
first: 'Stephen',
last: 'Merchant'
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2675 次 |
| 最近记录: |