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);


  • 如果想继承上面中drive方法

    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);

  • 但接收不到title
   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)