Javascript原型-object.create问题
我正在尝试了解object.create和原型继承,并具备以下功能:Javascript原型-object.create问题,javascript,Javascript,我正在尝试了解object.create和原型继承,并具备以下功能: var Employee = { 'attributes': {}, getAttributes: function() { return this.attributes; }, addAttribute: function(attribute) { if (! this.attributes.hasOwnProperty(attribute)) {
var Employee = {
'attributes': {},
getAttributes: function() {
return this.attributes;
},
addAttribute: function(attribute) {
if (! this.attributes.hasOwnProperty(attribute)) {
this.attributes.extend(attribute);
}
}
};
var OfficeEmployee = Object.create(Employee);
var OfficeEmployeeInstance = Object.create(OfficeEmployee, {'attributes': {'id': 123, 'name': 'Bob'}});
console.log(OfficeEmployeeInstance.attributes);
OfficeEmployeeInstance.addAttribute({'salary': '100'});
console.log(OfficeEmployeeInstance.getAttributes());
但它没有像我预期的那样工作,并抛出错误:
console.log(OfficeEmployeeInstance.attributes);
是未定义的
及
给出错误:
Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined tester.js:39
Employee.addAttribute tester.js:39
(anonymous function)
我做错了什么?
使用.create时,应向其传递someObject.prototype的参数,而不是构造函数名称。上面的文档应该会有所帮助。Object.create的第二个参数必须是properties对象。这是一个具有已定义结构和特定属性的对象:
var OfficeEmployeeInstance = Object.create(OfficeEmployee, {
'attributes': {
value: {'id': 123, 'name': 'Bob'},
writeable: true,
enumerable: true
}
});
您可以找到支持的属性。
this.attributes.extend
。什么是extend
?可能重复的?是否确实要在原型上创建具有instence特定成员的实例?我知道你在创建一个实例时会提供属性,但是你应该知道它们也存在于原型中,如果你不对它们进行阴影处理,你会得到意想不到的结果:这不是继承的意义吗?
var OfficeEmployeeInstance = Object.create(OfficeEmployee, {
'attributes': {
value: {'id': 123, 'name': 'Bob'},
writeable: true,
enumerable: true
}
});