了解 JavaScript 中的原型继承
我是JavaScript OOP的新手。您能解释一下以下代码块之间的区别吗?我测试了一下,两个块都有效。什么是最佳实践,为什么?
第一个块:
function Car(name){
this.Name = name;
}
Car.prototype.Drive = function(){
console.log("My name is " + this.Name + " and I'm driving.");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar;
function SuperCar(name){
Car.call(this, name);
}
SuperCar.prototype.Fly = function(){
console.log("My name is " + this.Name + " and I'm flying!");
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
第二块:
function Car(name){
this.Name = name;
this.Drive = function(){
console.log("My name is " + this.Name + " and I'm driving.");
}
}
SuperCar.prototype = new Car();
function SuperCar(name){
Car.call(this, name);
this.Fly = function(){
console.log("My name is " + this.Name + " and I'm flying!");
}
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
为什么作者使用 和 添加方法,而没有将它们声明为类内和类中的方法?Drive
Fly
prototype
this.Drive
Car
this.Fly
SuperCar
为什么需要设置回 ?设置时属性是否被覆盖?我注释掉了这句话,什么也没改变。SuperCar.prototype.constructor
SuperCar
constructor
prototype
为什么要调用构造函数?不会的属性和方法被“继承”,当我这样做Car.call(this, name);
SuperCar
Car
var myCar = new Car("Car");