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

时间:2015-07-13 14:04:27

标签: javascript function methods constructor call

我搜索过像我这样的问题,但它并没有很大帮助,因为每个人似乎都在询问(并回答)比我的查询更先进的东西(我在JavaScript的最底层)知识/技能)。

这是我的代码:

for

当我这样做时,我希望自己的信息能够自动打印

master.selected.allitems()

我不想执行这样的两个语句:

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

任何帮助表示赞赏。感谢。

2 个答案:

答案 0 :(得分:2)

只需在构造函数中调用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();
}

答案 1 :(得分:0)

您可以这样做:var myPoint = new xyPoint(10, 20).debugMessage();

JSFiddle

相关问题