简体   繁体   English

JavaScript原型继承

[英]Javascript- prototype inheritance

I don't understand something>Let's take a look at MDN's example: 我不了解某些内容>让我们看一下MDN的示例:

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +
                      this.name + ' with a negative price');
  }

  return this;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food; // Reset the constructor from Product to Food

Why I must write this part: 为什么我必须写这部分:

Food.prototype = Object.create(Product.prototype);
    Food.prototype.constructor = Food;

Isn't the Product.call(this, name, price); 不是Product.call(this, name, price); already copied that property(Prototype) from Product to Food? 已经将该属性(原型)从产品复制到食品了?

This is just how you do pseudoclassical instantiation of a class in JavaScript. 这就是在JavaScript中对类进行伪经典实例化的方式。 Lets first see what happens when you just do the first part, but lets add a bit for clarification: 首先让我们看看您刚完成第一部分时会发生什么,但让我们添加一些内容以进行澄清:

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +
                      this.name + ' with a negative price');
  }

  return this;
}

Product.prototype.declare = function () {
  console.log('I like ' + this.name);
} 

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

Run this in a console and and run console.dir(Product) vs console.dir(Food) . 在控制台中运行它,然后运行console.dir(Product) vs console.dir(Food) Food has some of the same properties as Product. 食品与产品具有某些相同的属性。 However, Food doesn't have access to the method "declare" that is on Product 's prototype. 但是, Food无法访问Product原型上的“声明”方法。 Thus, we need to set Food 's prototype. 因此,我们需要设置Food的原型。 Run this in console after the above code: 在上面的代码之后在控制台中运行此命令:

Food.prototype = Object.create(Product.prototype);

run console.dir for Food again. 再次为Food运行console.dir Now, Food has a prototype that has the same properties/methods as Product . 现在,Food的原型具有与Product相同的属性/方法。 However, the prototype's constructor is now 'Product'. 但是,原型的构造函数现在为“产品”。 The last step to fix this is setting Food.prototype.constructor so Food 's constructor is once again Food , but with all of the properties/methods of Product . 解决此问题的最后一步是设置Food.prototype.constructor使Food的构造函数再次是Food ,但具有Product所有属性/方法。

Food.prototype.constructor = Food;

It's a strange but logical process to attaining full inheritance with pseudoclassical instantiation in JavaScript. 在JavaScript中使用伪经典实例化实现完全继承是一个奇怪但逻辑的过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM