0

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?

416E64726577
  • 2,214
  • 2
  • 23
  • 47
Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • 1
    `this.attributes.extend`. What is `extend`? – thefourtheye Apr 21 '14 at 14:02
  • possible duplicate of [Object.create instead of Constructors for inheritance](http://stackoverflow.com/questions/16187072/object-create-instead-of-constructors-for-inheritance) – Bergi Apr 21 '14 at 14:40
  • Are you sure you want to create instances with instence specific member on the prototype? I know you provide attributes when you create an instance but you should know that they also exist on the prototype and if you don't shadow them you can get unexpected results: http://stackoverflow.com/a/16063711/1641941 – HMR Apr 21 '14 at 15:56
  • Isnt that the point of inheritance though? – Marty Wallace Apr 21 '14 at 16:06

2 Answers2

1

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.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
0

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.

lwalden
  • 813
  • 7
  • 11