如何在Javascript中从另一个成员函数调用成员函数

时间:2011-02-15 14:24:14

标签: javascript

说我有一些像这样的代码

function Chart(start, end, controller, method, chart)
{
    console.log('Chart constructor called');
    this.start = start;
    this.end = end;
    this.controller = controller;
    this.method = method;
    this.chart = chart;
    this.options = {};
}

Chart.prototype.update = function()
{
    console.log('update ' + new Date().getTime());
    $.getJSON('index.php', {
        controller: this.controller,
        method: this.method,
        START: this.start,
        END: this.end },
        function(json) { this.draw(json); }); //<-- Problem right here!
}              

Chart.prototype.draw = function(json)
{
    //lots of code here
}

我收到错误Uncaught TypeError: Object #<an Object> has no method 'draw'。现在,我是第一个承认我对Javascript很新的人。我应该以另一种方式调用成员函数吗?或者我应该做一些完全不同的事情?

编辑:这是我创建对象的方式:

chartObj = new Chart(start, end, 'OBF.RootCauses', 'ajaxRootCauses', chart);

2 个答案:

答案 0 :(得分:6)

这里的问题是this因为你正在定义一个新函数而被更改 - 所以this指的是你所在的函数。

还有其他方法可以解决这个问题,但最简单的方法是将this保存到变量并在该变量上调用函数,如下所示:

Chart.prototype.update = function()
{
    console.log('update ' + new Date().getTime());
    var self = this;
    $.getJSON('index.php', {
        controller: this.controller,
        method: this.method,
        START: this.start,
        END: this.end },
        function(json) { self.draw(json); });
} 

请参阅克里斯的答案,找出解决同一问题的不同方法。

答案 1 :(得分:3)

由于您已经在使用jQuery,因此可以更改此行

function( json ) { this.draw( json ); });

到此:

$.proxy( this.draw, this ) );

这将保留调用函数的上下文(即,此变量)。