Add function to JavaScript object using Object.Create

I am trying to use Object.Create in JavaScript. I currently have the following code:

var vehicle = { getModel: function () { console.log( "The model of this vehicle is.." + this.model ); } }; var car = Object.create(vehicle, { "id": { value: 9, }, "model": { value: "Ford", } }); var van = Object.create(vehicle, { "id": { value: 10, }, "model": { value: "Big Van", enumerable: true }, "make": { value: "Warrior", }, "getMake": function () { console.log( "The make of this vehicle is.." + this.make ); } }); 

I tried adding a function to van for getMake, but getting an error:

TypeError: property 'getMake' of object # is not a function when called:

van.getMake ();

Is it possible? How do you do this?

+4
source share
2 answers

Properties created in this way are not enumerated by default. This can cause problems.

Try this one (untested):

 "getMake": { value: function () { console.log( "The make of this vehicle is.." + this.make ) }, enumerable: true }; 

Change This seems to work because we are passing an object, not just a value. Enumerated is not necessary.

+5
source

You need to pass an object that defines the property, not just the value:

  "getMake": {value:function () { console.log( "The make of this vehicle is.." + this.make ); }} 

Reference

Note that the usual way to do OOP in Javascript is not using Object.create, but when using prototype .

+2
source

All Articles