【问题标题】:Is JavaScript Supporting the constructor overloading concept? [duplicate]JavaScript 是否支持构造函数重载概念? [复制]
【发布时间】:2018-12-18 04:26:23
【问题描述】:
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?**

我得到这个代码作为成功输出,但是当我改变构造函数的顺序时,我得到一个错误

【问题讨论】:

  • 没有。函数和方法重载不存在。
  • 由于 Javascript 能够允许忽略参数。即 funcX(var1, var2) 可以有效地使用 funcX() 调用,您有效地重载。您需要保护和初始化未传递的变量。
  • 我已经编辑了代码,请检查并给出明确的答案

标签: javascript reactjs


【解决方案1】:

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

【讨论】:

    【解决方案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']}`)
    

    【讨论】:

    • 仍然是Uncaught SyntaxError: A class may only have one constructor
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多