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']}`)

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

我将此代码作为成功输出,但是当我更改构造函数的顺序时,我会收到一个错误

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

是的,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']}`)

最新更新