1

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.

3
  • 1
    there's no prototypejs there that I can see Commented Jul 26, 2013 at 13:10
  • 1
    you will also have problems with their being both a method (in the prototype) called accelerate and a property with the same name. Commented Jul 26, 2013 at 13:10
  • @Alnitak: Good points both. I fixed the tags. Commented Jul 26, 2013 at 13:15

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@RommelCastro: If you're interested in inheritance in JavaScript, you may be interested in my Lineage script -- possibly to use it, or possibly just to see the comparison of Lineage vs. straight JavaScript, which demonstrates some things around how you handle inheritance, supercalls, etc.

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.