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.

4

1 回答 1

4

您永远不会调用其中的任何一个Car或您分配给的函数this.constructorCar因此其中的代码永远不会运行,并且您看不到_valaccelerate在任何对象上。

你做它的方式通常不是你做构造函数的方式。通常的事情是作为Car构造函数,例如:

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

当然,对于构造函数,您不需要使用Object.create. 只需通过以下方式调用该函数new

var myCar = new Car(42);

这大致相当于:

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

通常,当您使用 时Object.create,您没有像构建器那样拥有构造函数,如下所示:

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);
于 2013-07-26T13:09:57.913 回答