//ES5的做法:
//function Car(options){
// this.style = options.style;
//}
//
//Car.prototype.owner = function(){
// return "ivan";
//}
//
//
//const car = new Car({style:"cool"});
//
//console.log(car.style);
//console.log(car.owner());
//
//function BMW(options){
// var self = this;
// Car.call(self,options);
// this.color = options.color;
//}
//
//BMW.prototype = Object.create(Car.prototype);
//BMW.prototype.constructor = BMW;
//
//const bmw = new BMW({color: "red", style: "bigger"});
//
//console.log(bmw);
//console.log(bmw.owner());
//ES6的做法
class Car{
constructor({style}){
this.style = style;
}
owner(){
return "ivan";
}
}
//const car = new Car({style : "cool"});
//console.log(car);
//console.log(car.owner());
class BMW extends Car{
constructor(options){
super(options);
this.color = options.color;
}
}
const bmw = new BMW({style:"bigger", color :"red"})
console.log(bmw);
console.log(bmw.owner());
//function Car(options){
// this.style = options.style;
//}
//
//Car.prototype.owner = function(){
// return "ivan";
//}
//
//
//const car = new Car({style:"cool"});
//
//console.log(car.style);
//console.log(car.owner());
//
//function BMW(options){
// var self = this;
// Car.call(self,options);
// this.color = options.color;
//}
//
//BMW.prototype = Object.create(Car.prototype);
//BMW.prototype.constructor = BMW;
//
//const bmw = new BMW({color: "red", style: "bigger"});
//
//console.log(bmw);
//console.log(bmw.owner());
//ES6的做法
class Car{
constructor({style}){
this.style = style;
}
owner(){
return "ivan";
}
}
//const car = new Car({style : "cool"});
//console.log(car);
//console.log(car.owner());
class BMW extends Car{
constructor(options){
super(options);
this.color = options.color;
}
}
const bmw = new BMW({style:"bigger", color :"red"})
console.log(bmw);
console.log(bmw.owner());
本文通过实例对比了ES5与ES6中实现继承的不同方式。ES5使用构造函数和原型链来创建对象及定义方法,而ES6引入了更简洁的class语法糖,简化了继承的实现过程。
793

被折叠的 条评论
为什么被折叠?



