简体   繁体   中英

Add Function to JavaScript Object using Object.Create

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?

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.

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 .

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