从原型继承的正确方法是什么?

问题描述 投票:0回答:1

我有2个“课程”:

const Person = function(firstName, birthYear){
  this.firstName = firstName;
  this.birthYear = birthYear;
}
Person.prototype.sayHi = function(){
  console.log('Hi!');
}

还有

const Student = function(firstName, birthYear, course){
  Person.call(this, firstName, birthYear)
  this.course = course;
};

根据我从我正在做的课程中学到的知识,如果我想让

Student
继承
Person
的行为,我应该这样写:

Student.prototype = Object.create(Person.prototype);

我的问题是:这有什么区别:

Student.prototype = Object.create(Person.prototype);

还有这个:

Student.prototype = Person.prototype;
javascript oop prototype prototypejs prototypal-inheritance
1个回答
0
投票

一个是重复项,另一个是指针。当您更改其中一个而影响或不影响另一个时,就会感受到差异。具体来说,更改未复制原型的子级会影响父级。

我们来测试一下:

const Person = function(firstName, birthYear) {
  this.firstName = firstName;
  this.birthYear = birthYear;
}
Person.prototype.sayHi = function() {
  console.log('Hi!');
}

var person = new Person();

const Student1 = function(firstName, birthYear, course) {
  Person.call(this, firstName, birthYear)
  this.course = course;
};

const Student2 = function(firstName, birthYear, course) {
  Person.call(this, firstName, birthYear)
  this.course = course;
};

Student1.prototype = Object.create(Person.prototype);
Student2.prototype = Person.prototype;
var stud1 = new Student1()
var stud2 = new Student2()

// now we change person
Person.prototype.another = function() {
  console.log('Another Hi!');
}
Person.prototype.num = 12

// so who's got it?
stud1.another()
stud2.another()

// both! because a prototype points to functions
// but the other way would affect the parent
Student2.prototype.another = function() {
  console.log("I affected parent - ver 2");
}
Student1.prototype.another = function() {
  console.log("I affected parent - ver 1");
}

console.log (Student2.prototype.another == Student1.prototype.another)  // false
person.another()

© www.soinside.com 2019 - 2024. All rights reserved.