微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在JavaScript中创建实例的实例

我想制作一组不同人可以容纳的汽车的独特实例.汽车将具有相似的基本规格,但它们的一些属性方法会有所不同.

我遇到的问题是我无法弄清楚它应该如何工作.您如何在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');

};

弗雷德的法拉利是法拉利的一个例子,这是一个汽车的例子.问题是我想不出让构造函数构建构造函数方法.有没有办法做到这一点,或者我只是以错误的方式解决这个问题?

其他说明:

我知道我基本上可以让每种类型的汽车都是一个类似静态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;

工作原理:

>法拉利是一个构造函数,在调用时,调用Car来引用新实例,以及Car需要的参数. Car会在实例上设置这些属性.然后我们继续使用法拉利的代码,该代码接受传入的参数并且(在上面)将它们记为属性.
>我们确保将由新法拉利(取自Ferrari.prototype)分配给实例的对象使用Car.prototype作为其原型对象,这样如果您向Car.prototype添加内容,它们将出现在法拉利也是如此.
>我们确保Ferrari.prototype上的标准构造函数属性指的是法拉利.

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

原文地址:https://www.jb51.cc/js/156902.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐