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

时间:2016-04-17 13:06:05

标签: 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);

由于显而易见的原因,这会导致此错误。我知道它不是构造函数(见下文)。

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的一些理解,但如果有人能指出我正确的方向,那将会很棒。

2 个答案:

答案 0 :(得分:5)

您正在寻找的是派生构造函数和相关原型,有时称为子类

在老式的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引用新实例,以及Car所需的参数。 Car在实例上设置这些属性。然后我们继续使用Ferrari的代码,它接受传入的参数和(在上面)将它们记为属性。

  • 我们确保new Ferrari(取自Ferrari.prototype)将分配给实例的对象使用Car.prototype作为其原型对象,这样如果添加Car.prototype的内容,它们也会出现在Ferrari上。

  • 我们确保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;
    }
}

答案 1 :(得分:-1)

如果希望namespace WelcomeBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use \Symfony\Component\Security\Core\User\AdvancedUserInterface; use JMS\SerializerBundle\Annotation\Type; /** * Utilisateur * * @ORM\Table(name="utilisateur") * @ORM\Entity */ class Utilisateur extends BaseUser implements AdvancedUserInterface, \Serializable { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ protected $id; /** * @var string * * @ORM\Column(name="nom", type="string", length=40, nullable=false) */ protected $nom; /** * @var string * * @ORM\Column(name="prenom", type="string", length=40, nullable=false) */ protected $prenom; /** * @var integer * * @ORM\Column(name="numtelphone", type="integer", nullable=true) */ protected $numtelphone; /** * @var string * * @ORM\Column(name="addresse", type="string", length=40, nullable=true) */ protected $addresse; /** * @var integer * * @ORM\Column(name="jeton", type="integer", nullable=true) */ protected $jeton; /** * @var string * * @ORM\Column(name="photo", type="blob", nullable=true) */ protected $photo; /** * @var string * * @ORM\Column(name="mailreclamation", type="string", length=50, nullable=true) */ protected $mailreclamation; public function __construct() { parent::__construct(); // your own logic } public function getId() { return $this->id; } public function getNom() { return $this->nom; } public function getPrenom() { return $this->prenom; } public function getNumtelphone() { return $this->numtelphone; } public function getAddresse() { return $this->addresse; } public function getJeton() { return $this->jeton; } public function getPhoto() { return $this->photo; } public function getMailreclamation() { return $this->mailreclamation; } public function setId($id) { $this->id = $id; } public function setNom($nom) { $this->nom = $nom; } public function setPrenom($prenom) { $this->prenom = $prenom; } public function setNumtelphone($numtelphone) { $this->numtelphone = $numtelphone; } public function setAddresse($addresse) { $this->addresse = $addresse; } public function setJeton($jeton) { $this->jeton = $jeton; } public function setPhoto($photo) { $this->photo = $photo; } public function setMailreclamation($mailreclamation) { $this->mailreclamation = $mailreclamation; } public function json_encode() { return json_encode(array( $this->password, $this->salt, $this->usernameCanonical, $this->username, $this->expired, $this->locked, $this->credentialsExpired, $this->enabled, $this->id, )); } } 实例是构造函数,Car必须返回构造函数。

问题是它会继承Car而不是Function.prototype。如果这是不受欢迎的,请使用Car.prototype来修复它:

Object.setProtetypeOf

或者,您可以添加一个方法,用于“实例化”您的实例。

function Person() {
  this.cars = {};
}
function Car(make, country) {
  var instance = function(currentPrice, miles) {
    this.currentPrice = currentPrice;
    this.miles = miles;
  };
  instance.make = make;
  instance.country = country;
  Object.setPrototypeOf(instance, Car.prototype); // slow!!
  return instance;
}
var Ferrari = new Car('Ferrari', 'Italy');
var fred = new Person();
fred.cars.ferrari = new Ferrari(1200, 300000);