Search code examples
javascriptnew-operator

Javascript new keyword


What does it mean when the instance is created in the following way?

somevar = new Person.doSomething()

is this a shortcut to create the instance and call the method , like

person = new Person ()
person.doSomething()

or is it something else?

Thanks in advance.


Solution

  • No, this does not create a new instance of Person and then call a method on it. It creates an instance of whatever Person.doSomething() is. So, in effect, you these two are equivalent:

    const Person = {
      doSomething: function(foo, bar){
        this.foo = foo;
        this.bar = bar;
      }
    }
    
    //create a new instance of `Person.doSomething`
    const p1 = new Person.doSomething(1, "one");
    
    //take a reference of `Person.doSomething`
    const temp = Person.doSomething;
    //create an instance of it
    const p2 = new temp(2, "two");
    
    console.log("p1:", p1);
    console.log("p1 instanceof Person.doSomething:", p1 instanceof Person.doSomething);
    
    console.log("p2:", p2);
    console.log("p2 instanceof Person.doSomething:", p2 instanceof Person.doSomething);

    You can only get instances using constructable functions. These are plain functions (declared with the function keyword) and class constructors:

    function PlainConstructable(a, b) {
      this.foo = a;
      this.bar = b;
    }
    
    const plainInstance = new PlainConstructable("plain", "instance");
    
    class ClassConstructable {
      constructor(a, b) {
        this.foo = a;
        this.bar = b;
      }
    }
    
    const classInstance = new ClassConstructable("class", "instance");
    
    
    console.log(`plainInstance:
      instanceof PlainConstructable: ${plainInstance instanceof PlainConstructable}
      what it holds: ${JSON.stringify(plainInstance)}`);
      
    console.log(`classInstance:
      instanceof ClassConstructable: ${classInstance instanceof ClassConstructable}
      what it holds: ${JSON.stringify(classInstance)}`);

    Non-constructable are:

    const arrowFunction = () => {};
    
    const plainObject = {
      shorthandMethod() {}
    }
    
    try {
      new arrowFunction();
      console.log("Constructing arrow function successful.");
    } catch(e) {
      console.log(
        `Cannot construct arrow function
         ${e}`
       )
    }
    
    try {
      new plainObject.shorthandMethod();
      console.log("Constructing shorthand method successful.");
    } catch(e) {
      console.log(
        `Cannot construct shorthand method
         ${e}`
       )
    }
    
    try {
      new parseInt();
      console.log("Constructing built-in successful.");
    } catch(e) {
      console.log(
        `Cannot construct built-in
         ${e}`
       )
    }

    For more information about constructable functions