Search code examples
javascriptfunctionnew-operatorself-invoking-function

Call the new Operator be called individually without assigning to a variable in JavaScript?


I am new to JS and having a piece of JavaScript codes from a tutorial:

class TypeWriter{
      
      constructor(x,y){
           this.x = x;
           this.y = y;
           this.type();
   }
}

TypeWriter.prototype.type() = function(){......}

So far it's all good, but then I got confused by how the new operator is called:

function init(){
      const a,b;
      new TypeWriter(a,b);
}

The function works well and the type() method is invoked automatically, which makes me lost. What 's the reason behind it? Why the type() is invoked by just calling the new TypeWriter()?

In my understanding, the type() and the new operator should be like this:

const typeWriter = new TypeWriter(a,b);
typeWriter.type();

Can anyone explain how it works to me? Thank you in advance.


Solution

  • When you instantiate an object of a class using the new keyword, you are basically calling the constructor of that class. And all the code in the constructor will run.

    So, this is how the constructor looks like:

    this.x = x;
    this.y = y;
    this.type();
    

    The two arguments that you pass to the constructor are added as properties of the object (x, y). Now, in the third line you call the type method which is why the type method is being called immediately when you instantiate.

    Also, there's a small error to how you're adding the type method to the prototype, you don't put parenthesis after type. (see the snippet below)

    class TypeWriter {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.type();
      }
    }
    
    TypeWriter.prototype.type = function() {
      console.log("Type method called");
    }
    
    const typeWriter = new TypeWriter(10, 20); // Method called once
    typeWriter.type(); // Method called again

    If you don't want to call the type method while instantiating you can simply remove its call from the constructor. (see the snippet below)

    class TypeWriter {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      }
    }
    
    TypeWriter.prototype.type = function() {
      console.log("Type method called");
    }
    
    const typeWriter = new TypeWriter(10, 20);
    typeWriter.type(); // Method called once