javascript - 为什么继承在javascript中没有标准方式,为什么它有不同的定义方式以及每种方式的方面是什么?
问题描述
我的问题是:为什么定义继承的所有 3 种方式之间存在差异?如果第一个片段是最正确的片段,那么 2015 年之前的人们如何处理新关键字?
- 第一个片段对象 y 是大猩猩的实例,它具有动物的原型和方法,动物从对象原型继承
注意:名称,年龄在对象本身上定义 - 第二个片段与第一个片段相同,但不同之处在于它在 Animal 原型名称、年龄上具有附加属性,并且它们都具有未定义的值与新调用。
- 第三个片段完全不同,它具有 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);
解决方案
推荐阅读
- java - JPanel、2D 图形和 MouseListener 遇到问题
- tensorflow - 卷积神经网络得到一个值错误
- wpf - 是否可以更改 WPF 元素的边界?
- ios - 错误 ibtoold[1345:11688] 调试:添加到环境:(在 IOS 中运行 xamarin 表单时出错)
- nginx - 用于内部/外部 docker-compose 的 Nginx 上游服务器
- java - 如何在没有原始对象引用的情况下复制 java 中的对象?
- python-3.x - 计算网格中从左上到右下的路径数
- html - 如何使用查询选择器选择没有特定类名的元素?
- android - API 字符串不返回值
- python - MySQLdb._exceptions.OperationalError: (2059,
) flask_mysqldb