4

I'm 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've tried to add a function to van for getMake but I get the error:

TypeError: Property 'getMake' of object # is not a function when I call:

van.getMake();

Is this possible? How do you do it?

2
  • 2
    I have never used Object.create... Commented Nov 26, 2012 at 13:01
  • Not only have I never used it, but I didn't know it even existed... Commented Nov 26, 2012 at 13:05

2 Answers 2

6

Properties created that way are not enumerable by default. This may be causing your issue.

Try this(untested):

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

Edit It looks like this is working because we are passing an object and not just the value. The enumerable is unnecessary.

Sign up to request clarification or add additional context in comments.

3 Comments

No need for the property to be enumerable.
I'm with @dystroy, I'd even argue that the property is best defined as enumerable: false, when iterating an object (for (var p in obj)), you generally don't want to deal with the methods
But the default behaviour is to list all enumerable properties, and methods are enumerable by default.So its good to go with the enumerable:true as it is more towards the expected default behaviour.
2

You need to pass an object defining 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 isn't in using Object.create but in using prototype.

1 Comment

In my own opinion it's ugly, useless and slow. But, as most js coders I never use Object.create so I may miss some of its advantages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.