简体   繁体   English

如何从构造函数中调用方法

[英]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). 我一直在搜索像我这样的问题,但它并没有很大帮助,因为每个人似乎都在询问(并回答)比我的查询更先进的东西(我处于最低级别的JavaScript知识/技能)。

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: 只需在构造函数中调用debugMessage:

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(); 你可以这样做: var myPoint = new xyPoint(10, 20).debugMessage();

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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