Javascript原型 - object.create问题

时间:2014-04-21 13:51:31

标签: javascript

我试图了解object.create和prototypal继承,并有以下内容:

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)

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

Object.create的第二个参数必须是属性对象。这是一个具有已定义结构和特定属性的对象:

var OfficeEmployeeInstance = Object.create(OfficeEmployee, {
       'attributes': {
           value: {'id': 123, 'name': 'Bob'},
           writeable: true,
           enumerable: true
       }
    });

您可以找到支持的属性here

答案 1 :(得分:0)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

使用.create时,你应该传递someObject.prototype的参数,而不是构造函数名称。上面的文档应该有所帮助。

相关问题