How to call a method from a constructor

I was looking for a question like mine, but it didn't help much because everyone seems to be asking (and answering) something more advanced than my request (I'm at the lowest level of JavaScript knowledge / skill).

Here is my code:

function xyPoint(x, y){
    this.x = x;
    this.y = y;
    this.debugMessage = function(){
        document.getElementById("messageArea").innerHTML =
                "xyPoint(x, y) constructor called";
    };
}

      

I want my informative message to be automatically printed when I do

var myPoint = new xyPoint(10, 20);

      

I don't want to execute two statements:

var myPoint = new xyPoint(10, 20);
myPoint.debugMessage();

      

Any help is appreciated. Thank.

+3


source to share


2 answers


Just call debugMessage in the constructor:



function xyPoint(x, y){
    this.x = x;
    this.y = y;
    this.debugMessage = function(){
        document.getElementById("messageArea").innerHTML =
                "xyPoint(x, y) constructor called";
    };
    this.debugMessage();
}

      

+2




You can do it like: var myPoint = new xyPoint(10, 20).debugMessage();



JSFiddle

0









All Articles