3

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.

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

JSFiddle

1 Comment

The message is printed, but the variable myPoint is undefined (because the debugMessage method returns nothing). Try calling alert(myPoint); at the end of your script.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.