了解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");
陪伴而非守候
狐的传说
随时随地看视频慕课网APP
相关分类