Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method from within a constructor

I've searched for a question like mine, but it hasn't been very helpful because everyone seems to be asking (and answering) something a bit more advanced than my query (I'm at the very bottom level of JavaScript knowledge/skills).

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 print automatically when I do

var myPoint = new xyPoint(10, 20);

I don't want to have to execute two statements like this:

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

Any help appreciated. Thanks.

like image 921
rippon Avatar asked Jun 25 '26 19:06

rippon


1 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();
}
like image 70
Glorfindel Avatar answered Jun 27 '26 07:06

Glorfindel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!