简体   繁体   中英

Javascript prototype - object.create issue

Im trying to learn about object.create and prototypal inheritance and have the following:

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());

It doesnt work as i expect it should though and throws errors:

console.log(OfficeEmployeeInstance.attributes);

is undefined

and

 console.log(OfficeEmployeeInstance.getAttributes());

gives error:

Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined tester.js:39
Employee.addAttribute tester.js:39
(anonymous function)

What am i doing wrong here?

The second argument of Object.create has to be a properties object. That's an object with a defined structure and specific properties:

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

You can find the supported properties here .

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

When using .create you should pass it an argument of someObject.prototype, rather than a constructor name. The documentation above should help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM