JavaScript OOP 参考方法



早上好,所以,我正在从JavaScript的函数式编程方法转向面向对象的方法,我有一个问题。 在函数式编程中,我可以在另一个函数示例中调用一个函数:

function a(){
    // do something and when done call function b
    b();
}
function b(){ 
    // does more stuff 
}

现在我正在切换到 OOP 方法,我将如何从同一对象中的另一个方法调用对象中的方法。 例如:

var myClass = function(){
    this.getData = function(){
        //do a jquery load and on success call the next method
        $('#a').load('file.asp',function(response,status,xhr){
            switch(status){
                case "success":
                    //THIS IS WHERE THE QUESTION LIES
                    this.otherfuntcion();
                break;
            }
        }
    }
    this.otherfunction = new function(){
        // does more stuff
    }
}
p = new myClass();
p.getData();

我可以在成功调用方法 b 时说 this.b() 还是我必须做其他事情? 提前谢谢你。

使用更多的方法和很多实例,这将非常慢。请改用原型:

var myClass = function(){
}
myClass.prototype = {
    getData: function(){
        //do a jquery load and on success call the next method
        $('#a').load('file.asp',function(response,status,xhr){
            switch(status){
                case "success":
                    //THIS IS WHERE THE QUESTION LIES
                    this.otherfunction();
                break;
            }
        }.bind(this))
    },
    otherfunction: new function(){
        // does more stuff
    }
};

p = new myClass();
p.getData();

匿名回调函数中的this上下文与类方法中的上下文不同。因此,您需要在闭包中保留对上下文的引用:

var that = this;
$('#a').load('file.asp',function(response,status,xhr){
    switch(status){
        case "success":
            //THIS IS WHERE THE QUESTION LIES
            that.otherfuntcion();
        break;
    }
});

另一种方法是将特定上下文绑定到您的匿名函数:

$('#a').load('file.asp',function(response,status,xhr){
    switch(status){
        case "success":
            //THIS IS WHERE THE QUESTION LIES
            this.otherfuntcion();
        break;
    }
}.bind(this));

您应该将外部函数上下文复制到新变量中以直接引用外部上下文。 内部函数中的this是此内部函数的上下文。

var self = this;
$('#a').load('file.asp',function(response,status,xhr){
    switch(status){
        case "success":
            //THIS IS WHERE THE QUESTION LIES
            self.otherfuntcion();
        break;
    }
}

最新更新