vol*_*air 6 javascript inheritance
我正在研究Javascript中的继承概念,我正在看的教程使用这段代码:
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么有必要同时调用父构造函数Person.call(this),并将Student原型设置为等于新Person对象(即Student.prototype = new Person();)?
小智 5
有两个单独的问题需要处理.
第一个是确保新Student对象继承自Person对象.这就是你这样做的原因Student.prototype = new Person().这使得Student.prototype一个Personso Student对象将继承该对象继承的任何内容(from Person.prototype).
第二种是将Person构造函数中的任何行为应用于任何新Student对象.这就是你这样做的原因Person.call(this).如果Person构造函数没有任何修改新对象的代码,这在技术上是不需要的,但是如果你Person稍后添加一些代码,它仍然是一个好主意.
旁注,在设置继承时,最好这样做:
Student.prototype = Object.create(Person.prototype)
Run Code Online (Sandbox Code Playgroud)
...... Object.create如果需要可以垫片.这样,您实际上不需要调用Person构造函数来获取继承自的新对象Person.prototype.同样,有时候不是问题,但有时在构造函数中存在设置继承时不希望出现的副作用.