[英]Javascript prototype - object.create issue
我正在尝试学习object.create和原型继承,并具有以下内容:
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);
未定义
和
console.log(OfficeEmployeeInstance.getAttributes());
给出错误:
Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined tester.js:39
Employee.addAttribute tester.js:39
(anonymous function)
我在这里做错了什么?
Object.create
的第二个参数必须是属性对象。 那是一个具有定义的结构和特定属性的对象:
var OfficeEmployeeInstance = Object.create(OfficeEmployee, {
'attributes': {
value: {'id': 123, 'name': 'Bob'},
writeable: true,
enumerable: true
}
});
您可以在此处找到受支持的属性。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
使用.create时,您应该向其传递someObject.prototype的参数,而不是构造函数的名称。 上面的文档应该有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.