我正在通过 Udemy 类(class)学习 JavaScript 中的 Object.create 和继承,但我有一个误解。我想问你是否可以帮助我理解它是如何工作的。提前致谢!
例如我有这行简单的代码:
var Person = function(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
};
Person.prototype.calculateAge = function() {
var age = new Date().getFullYear() - this.yearOfBirth;
console.log(age);
};
var Athlete = function(name, yearOfBirth, job, olympicGames, medals) {
Person.call(this, name, yearOfBirth, job);
this.olympicGames = olympicGames;
this.medals = medals;
};
Athlete.prototype = Object.create(Person.prototype);
Athlete.prototype.constructor = Athlete;
var objAthlete = new Athlete('Mark', 1990, 'swimmer', 3, 10);
我想问你是否必须要放这行代码:
Person.call(this, name, yearOfBirth, job);
我可以使用以下代码更改 Athlete 构造函数吗:
var Athlete = function(name, yearOfBirth, job, olympicGames, medals) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
this.olympicGames = olympicGames;
this.medals = medals;
};
我理解为什么我们使用 Object.create 以及为什么我们将正确的值分配给原型(prototype)的构造函数属性,但我不明白这行代码是否是强制性的。
另一个问题是关于 _ proto _,我知道原型(prototype)和“dunder”原型(prototype),但在以下情况下我不明白。
例如,如果我编写 console.dir(abjAthlete)
,我会在控制台中得到以下输出:
讲师说原型(prototype)是Person,也就是说Athlete函数的构造函数原型(prototype)属性和Person原型(prototype)属性是一样的。这怎么可能,因为如果我写 Athlete.__proto__ === Person.prototype
我会收到 false。我非常感谢任何反馈!
最佳答案
I want to ask you if it is mandatory to put this line of code:
Person.call(this, name, yearOfBirth, job);
Can I change the Athlete constructor with the following code?
是的,你可以,而且它会产生完全相同的效果。但是,您现在可能已经复制了 Person
的初始化代码,这是一种不好的做法。 Don't repeat yourself并调用已经知道如何初始化这些属性的 Person
构造函数。
关于javascript - JavaScript 中的 Object.create 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360674/