Javascript 使用Prototype创建()对象

Javascript 使用Prototype创建()对象,javascript,prototype,prototypal-inheritance,Javascript,Prototype,Prototypal Inheritance,我一直在玩javascript中的Inherantion,现在我在玩Object.create,我得到了这个场景 var Car = function() { this.constructor = function(value) { this._val = value; this.accelerate = false; }; }; Car.prototype.accelerate = function() { this.accelerate = true; };

我一直在玩javascript中的Inherantion,现在我在玩Object.create,我得到了这个场景

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);
如果我尝试myCar.getVal()不工作,我会得到一个错误,说明该对象中不存在该方法?为什么会发生这种情况?最后,使用Object.create()的正确方法是什么


致以最诚挚的问候。

您从未调用过
汽车
或分配给
此函数的函数。
汽车
中的构造函数
,因此其中的代码从未运行过,并且您在任何对象上都看不到
\u val
加速

你做这件事的方式通常不是你做构造函数的方式。通常情况下,
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);

您从未调用
Car
或分配给
this.constructor的函数,因此
Car
中的代码从未运行过,并且在任何对象上都看不到
\u val
accelerate

你做这件事的方式通常不是你做构造函数的方式。通常情况下,
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);

这里没有prototypejs,我可以看到您也会遇到问题,因为它们既是名为
accelerate
的方法(在原型中),又是同名的属性。@Alnitak:两者都很好。我修复了标记。我看不到prototypejs。它们既是名为
accelerate
的方法(在原型中)又是同名属性,这两个方面都有问题。@Alnitak:这两点都很好。我修复了标记。@RommelCastro:如果你对JavaScript中的继承感兴趣,你可能会对我的脚本感兴趣——可能是为了使用它,也可能只是为了看看,它演示了一些关于如何处理继承、超级调用等的事情。@RommelCastro:如果你对JavaScript中的继承感兴趣,您可能对我的脚本感兴趣——可能是为了使用它,也可能只是为了看看,它演示了一些关于如何处理继承、超级调用等的内容。