-1
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?**

I am getting this code as success output but when i change the sequence of constructors , i am getting an error

3
  • 2
    No. Function and method overloading do not exist. Commented Dec 18, 2018 at 4:28
  • As Javascript is able to allow parameters to be ignored. ie funcX(var1, var2) can be validly called using funcX() you effectively have overloading. You would need to protect and initialize variables not passed tho. Commented Dec 18, 2018 at 4:36
  • I have edited the code , please check and give a clarified answer Commented Dec 18, 2018 at 4:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-2

Yes JavaScript supports the constructor overloading concept but Partially. It works according to bottom up Approach so it will work according to sequence of constructors.

The Code below will run according to the bottom up approach and will execute the output according to it.

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

1 Comment

It's still an Uncaught SyntaxError: A class may only have one constructor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.