jam*_*mcd 7 javascript oop constructor instances
我想制作一组不同人可以容纳的汽车的独特实例.汽车将有类似的基本规格,但他们的一些属性和方法会有所不同.
我遇到的问题是我无法弄清楚它应该如何工作.您如何在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);
Run Code Online (Sandbox Code Playgroud)
出于显而易见的原因,这会导致此错误.我知道它不是构造函数(见下文).
Uncaught TypeError: Ferrari is not a constructor
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是这样的.法拉利的每个不同实例都有不同的价格和价格.
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');
};
Run Code Online (Sandbox Code Playgroud)
弗雷德的法拉利是法拉利的一个例子,这是一个汽车的例子.问题是我想不出一种方法来使构造函数构建一个构造函数.有没有办法做到这一点,或者我只是以错误的方式解决这个问题?
其他说明:
我知道我基本上只需要使每种类型的汽车成为类似静态JSON的对象,然后创建它的实例并添加新的唯一值.但是,我希望能够将Car作为构造函数,这样我就可以在需要时轻松制作.
我在这里显然缺少对OOP或JavaScript的一些理解,但如果有人能指出我正确的方向,那将会很棒.
您正在寻找的是派生构造函数和相关原型,有时称为子类.
在老式的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;
Run Code Online (Sandbox Code Playgroud)
工作原理:
Ferrari
是一个构造函数,调用它时,调用Car
与this
参照新的实例,用参数一起Car
需求.Car
它在实例上设置这些属性.然后我们继续使用Ferrari
代码,它接受传入的参数和(在上面)将它们记为属性.
我们保证将被分配给实例对象new Ferrari
(这是取自Ferrari.prototype
)使用Car.prototype
其原型对象,因此,如果您添加的东西Car.prototype
,他们会出现在Ferrari
S以及.
我们确保标准constructor
属性Ferrari.prototype
是指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;
}
}
Run Code Online (Sandbox Code Playgroud)