首页 > 解决方案 > 为什么继承在javascript中没有标准方式,为什么它有不同的定义方式以及每种方式的方面是什么?

问题描述

我的问题是:为什么定义继承的所有 3 种方式之间存在差异?如果第一个片段是最正确的片段,那么 2015 年之前的人们如何处理新关键字?

  1. 第一个片段对象 y 是大猩猩的实例,它具有动物的原型和方法,动物从对象原型继承
    注意:名称,年龄在对象本身上定义
  2. 第二个片段与第一个片段相同,但不同之处在于它在 Animal 原型名称、年龄上具有附加属性,并且它们都具有未定义的值与新调用。
  3. 第三个片段完全不同,它具有 Object 的原型,就像将每个方法从动物原型移到自身一样。

考虑查看这些片段

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

Animal.prototype.eat = function () {
  console.log(`${this.name} is eating!`);
};

function Gorilla(name, age, action) {
  Animal.call(this, name, age);
}

Gorilla.prototype = Object.create(Animal.prototype);
Gorilla.prototype.constructor = Gorilla;

var y = new Gorilla("morphy", 50);
console.log(y);

以上片段图片

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

Animal.prototype.eat = function () {
  console.log(`${this.name} is eating!`);
};

function Gorilla(name, age, action) {
  Animal.call(this, name, age);
}

Gorilla.prototype = new Animal();
Gorilla.prototype.constructor = Gorilla;

var y = new Gorilla("morphy", 50);
console.log(y);

以上片段图片

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

Animal.prototype.eat = function () {
  console.log(`${this.name} is eating!`);
};

function Gorilla(name, age, action) {
  Animal.call(this, name, age);
}

Gorilla.prototype = Animal.prototype;
Gorilla.prototype.constructor = Gorilla;

var y = new Gorilla("morphy", 50);
console.log(y);

在此处输入图像描述

标签: javascript

解决方案


推荐阅读