JavaScript是否支持构造函数重载概念?

时间:2018-12-18 04:26:23

标签: javascript reactjs

class Camera {
    constructor(id){
        this.id = id;
    }

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

let camera = new Camera('A456','Karan');
let drone = new Camera('A1');


console.log(`camera: ${camera['id']} ${camera['name']}`)
console.log(`drone: ${drone['id']}`)



**IS the ABOVE code said as the constructor overloading?**

我正在获取此代码作为成功输出,但是当我更改构造函数的序列时,却出现了错误

2 个答案:

答案 0 :(得分:0)

// Our object declares all the properties it natively supports.
function Person(name, age, location) {
  this.name = name;
  this.age = age;
  this.location = location;

  // Deal with essential properties
  if(this.name === undefined) this.name = 'John Doe';
};

var paul = new Person("Paul");

var person = new Person();

console.log(paul);
console.log(person);

答案 1 :(得分:-2)

是的,JavaScript支持构造函数重载概念,但部分支持。 它根据自下而上的方法工作,因此将根据构造函数的顺序工作。

下面的代码将根据自下而上的方法运行,并将根据其执行输出。

class Camera {
    constructor(id){
        this.id = id;
    }

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

let camera = new Camera('A456','Karan');
let drone = new Camera('A1');


console.log(`camera: ${camera['id']} ${camera['name']}`)
console.log(`drone: ${drone['id']}`)