简体   繁体   中英

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.

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

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

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM