我是 JavaScript 面向对象编程的新手。你能解释一下以下代码块之间的区别吗?我测试过了,两块都能用。什么是最佳实践,为什么?
第一个街区:
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();
为什么作者使用 prototype
添加了 Drive
和 Fly
方法,而没有在 Car
类中将它们声明为 this.Drive
方法,在 SuperCar
类中将它们声明为 this.Fly
?
为什么 SuperCar.prototype.constructor
需要设置回 SuperCar
?设置 prototype
时是否重写 constructor
属性?我把这一行注释掉了,什么也没有改变。
为什么在 SuperCar
构造函数中调用 Car.call(this, name);
? 当我这样做时,Car
的属性和方法不会被“继承”吗
var myCar = new Car("Car");