设置在对象实例化后定义的方法

时间:2015-01-28 18:02:42

标签: javascript oop scope

如何定义在实例化对象后可以设置的对象的方法,但是,当事件发生时,从对象内的内部代码调用?

例如,我有一个像这样的构造函数:

function ExampleObject(){
    if(!(this instanceof ExampleObject)){
        throw "Error not called using the new keyword";
    }
    this.functionToCall; //set a function that can be defined later
    function init(){
        var xhr = new XMLHttpRequest();
        xhr.open("get", location, true);
        xhr.onreadystatechange = function(){
            if(typeof this.functionToCall !== "undefined"){//problem with use of "this" here?
                //...execute code...
            }
        };
        xhr.send();
     }
     init();
}

然后,我创建了这个Object的一个实例并设置了函数:

var example = new ExampleObject();
example.functionToCall = function(){/*some code*/};

但是,它永远不会到达if语句中的代码,看看函数是否已定义(if(typeof this.functionToCall !== "undefined"))。所以,似乎我的方法可能不是正确的方法。还有另一种方法来实现这一目标吗?如果是这样,为什么我的方法不起作用呢?

1 个答案:

答案 0 :(得分:0)

所以,我的方法还可以。我的问题与范围有关。首先,正如评论中所指出的那样,你调用条件(if(typeof this.onmessage !== "undefined"))确实很重要。如果在构造函数中调用它,则尚未定义this.onmessage。因此,必须在事件函数中调用它,这是我的问题出现的地方。

在我的事件功能中,我正在调用" typeof condition"使用this关键字。这里,this指的是事件函数的对象调用(在我的情况下" xhr")而不是构造函数定义的对象(ExampleObject)的实例。为了解决这个问题,我只是在构造函数中放置一个变量,该函数引用this的实例:

var that = this;

然后,我可以在具有不同范围的内部函数中使用此变量来引用ExampleObject实例。