class
ES5中创建对象以及继承
function Car(options){
this.title=options.title;
};
Car.prototype.drive=function(){
return 'run'
};
const car =new Car({title:'BMW'});
console.log(car);
console.log(car.drive());
继承
function Toyota(options){
this.color=options.color;
};
const toyota=new Toyota({color:'RED',title:'hello'});
console.log(toyota.title)//undefined
- 因为title没有定义,所以拿不到,需要借助Call
function Toyota(options){
Car.call(this,options)
this.color=options.color;
};
const toyota=new Toyota({color:'RED',title:'hello'});
console.log(toyota);
function Toyota(options){
Car.call(this,options)
this.color=options.color;
};
Toyota.prototype=Object.create(Car.prototype);
Toyota.prototype.constructor=Toyota;
const toyota=new Toyota({color:'RED',title:'hello'});
console.log(toyota.drive());
ES6中创建对象以及继承
class Car{
//构造函数
constructor({title}){
this.title=title
}
drive(){
return 'runing'
}
};
const car=new Car({title:'bmw'});
console.log(car)
继承
class Toyota{
constructor(e){
this.color=e.color
};
};
const toyota=new Toyota({color:"red",title:'hello'});
console.log(toyota);
class Toyota{
constructor(e){
super(e);//接收器
this.color=e.color
};
}
const toyota=new Toyota({color:"red",title:'hello'});
console.log(toyota);//Uncaught SyntaxError: 'super' keyword unexpected here
class Toyota extends Car{
constructor(e){
super(e);//接收器
this.color=e.color
};
};
const toyota=new Toyota({color:"red",title:'hello'});
console.log(toyota)