ES6类:不同的书写方式,相同的输出

时间:2019-01-14 08:53:31

标签: javascript class constructor super

我创建了Class Vehicle,并使用Class Car对其进行了扩展。但是,在扩展Class时,我使用不同的方法构造器()和super()来获得相同的输出-参见案例1至4。有人可以帮助我发现差异吗?

这是我到目前为止的结论:

    案例1和案例2相同。当省略构造函数()和super()时,默认情况下,系统在运行代码时将它们包括在内,并将所有参数从子类传递到父类。
  • 在情况3中,我实例化Car类,将“ Mercedes”作为值传递,而“ car”将覆盖Car类中的type变量。这意味着如果我第二次实例化Car类,并且这次通过“ Volvo”作为值,则结果将为
   let car = new Car('Volvo');
   console.log(car.getName() ); // This is the car's name: Volvo
   console.log(car.getType() ); // car
  • 在案例4中,我实例化了Car类,并用Car类中的nametype变量覆盖了两个值(“ Mercedes”和“ car”)。如果我实例化Car类,这次将“ Volvo”和“ moto”作为值传递,console.log结果仍将显示Merceds和car:
   let car = new Car('Volvo', 'moto');
   console.log(car.getName() ); // This is the car's name: Mercedes
   console.log(car.getType() ); // car

课程

    class Vehicle {
      constructor (name, type) {
        this.name = name;
        this.type = type;
      }
      getName () {
        return this.name;
      }
      getType () {
        return this.type;
      }
    }

扩展-情况1

    class Car extends Vehicle {
      getName () {
        return "This is the car's name: " + super.getName();
      }
    }

    let car = new Car('Mercedes', 'car');
    console.log( car.getName() ); // This is the car's name: Mercedes
    console.log( car.getType() ); // car

扩展-案例2

    class Car extends Vehicle {
      constructor (name, type) {
        super(name, type);
      }
      getName () {
        return "This is the car's name: " + super.getName();
      }
    }

    let car = new Car('Mercedes', 'car');
    console.log( car.getName() ); // This is the car's name: Mercedes
    console.log( car.getType() ); // car

扩展-情况3

    class Car extends Vehicle {
      constructor (name) {
        super(name, 'car');
      }
      getName () {
        return "This is the car's name: " + super.getName();
      }
    }

    let car = new Car('Mercedes');
    console.log( car.getName() ); // This is the car's name: Mercedes
    console.log( car.getType() ); // car

扩展-案例4

    class Car extends Vehicle {
      constructor (name) {
        super('Mercedes', 'car');
      }
      getName () {
        return "This is the car's name: " + super.getName();
      }
    }

    let car = new Car;
    console.log( car.getName() ); // This is the car's name: Mercedes
    console.log( car.getType() ); // car

0 个答案:

没有答案
相关问题