简体   繁体   中英

Object.create() with Prototype

i been playing with inheratance in javascript and right now i been playing with Object.create, and i got this scenerio

var Car = function() {
  this.constructor = function(value) {
    this._val = value;
    this.accelerate = false;
  };
};

Car.prototype.accelerate = function() {
  this.accelerate = true;
};

Car.prototype.getVal = function() {
  return this._val;
};

var myCar = Object.create(Car);

if i try myCar.getVal() don't work, i get an error saying that the method don't exist in that object? why this happens? and finally which is the right way to use Object.create()?

best regards.

You never call either Car or the function you're assigning to this.constructor within Car , so the code in it never runs, and you don't see _val or accelerate on any objects.

The way you've done it isn't usually how you do constructors. The usual thing is for Car to be the constructor, eg:

var Car = function(value) {  // Added parameter, otherwise `value` was coming from nowhere
  this._val = value;
  this.accelerating = false; // Side note: Changed so it doesn't conflict with the method
};

And of course, with constructor functions, you don't need to use Object.create . Just call the function via new :

var myCar = new Car(42);

That is roughly equivalent to this:

var myCar = Object.create(Car.prototype);
Car.call(myCar, 42);

Normally when you're using Object.create , you don't have constructor functions so much as builders, like this:

var carProto = {
  accelerate: function() {
    this.accelerating = true; // Side note: Changed so it doesn't conflict with the method
  },
  getVal: function() {
    return this._val;
  }
};

function Car(value) {
  var c = Object.create(carProto);
  c._val = value;
  return c;
}

var myCar = Car(42);

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