我想制作一组不同人可以拥有的汽车的独特实例。这些汽车将具有相似的基本规范,但它们的某些属性和方法会有所不同。
我遇到的问题是我不知道它应该如何工作。您如何在 JavaScript 中处理或创建实例的实例?
var Car = function(make, country) {
this.make = make;
this.country = country;
};
var Ferrari = new Car('Ferrari', 'Italy');
var fred = new Person() {};
var fred.cars['Ferrari'] = new Ferrari(1200, 300000);
由于显而易见的原因,这会导致此错误。我知道它不是构造函数(见下文)。
Uncaught TypeError: Ferrari is not a constructor
我正在寻找的是这样的东西。每一辆不同的法拉利实例都有不同的价格和里程数。
var Ferrari = function(currentPrice, miles) }
this.currentPrice = currentPrice;
this.miles = miles;
// this is an instance of car, aka it needs the result of this:
// new Car('Ferrari', 'Italy');
};
Fred 的 Ferrari 是 Ferrari 的一个实例,而 Ferrari 是 Car 的一个实例。问题是我想不出让构造函数构建构造函数的方法。有没有办法做到这一点,或者我只是以错误的方式解决这个问题?
其他注意事项:
我知道我基本上可以让每种类型的汽车成为一个类似 JSON 的静态对象,然后创建它的实例并添加新的唯一值。但是,我希望能够将 Car 保留为构造函数,以便在需要时可以轻松地制作更多内容。
我显然缺少对 OOP 或 JavaScript 的一些理解,但如果有人能指出正确的方向,那就太好了。
最佳答案
您正在寻找的是一个派生的构造函数和关联的原型(prototype),有时称为子类。
在老式的 ES5 中它看起来像这样:
var Car = function(make, country) {
this.make = make;
this.country = country;
};
var Ferrari = function(currentPrice, miles) {
Car.call(this, "Ferrari", "Italy");
this.currentPrice = currentPrice;
this.miles = miles;
};
Ferrari.prototype = Object.create(Car.prototype);
Ferrari.prototype.constructor = Ferrari;
工作原理:
Ferrari
是一个构造函数,当被调用时,调用Car
并使用this
引用新实例,以及argumentsCar
需要。Car
会在实例上设置这些属性。然后我们继续Ferrari
的代码,它接受传入的参数并(在上面)将它们记住为属性。我们确保将由
new Ferrari
分配给实例的对象(取自Ferrari.prototype
)使用Car.prototype
作为其原型(prototype)对象,因此如果您向Car.prototype
添加内容,它们也会出现在Ferrari
上。我们确保
Ferrari.prototype
上的标准constructor
属性引用Ferrari
。
在 ES2015 中更好(您现在可以通过转译使用它,例如使用 Babel 等工具):
class Car {
constructor(make, country) {
this.make = make;
this.country = country;
}
}
class Ferrari extends Car {
constructor(currentPrice, miles) {
super("Ferrari", "Italy");
this.currentPrice = currentPrice;
this.miles = miles;
}
}
关于javascript - 你如何在 JavaScript 中创建实例的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36676897/