Rommel Castro
Rommel Castro

Reputation: 460

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.

Upvotes: 1

Views: 242

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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, e.g.:

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);

Upvotes: 4

Related Questions