【问题标题】:JavaScript OOP reference approachJavaScript OOP 参考方法
【发布时间】:2014-02-26 15:41:11
【问题描述】:

早上好 SO,我正在从 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();

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

如果有更多方法和大量实例,这将非常慢。改用原型:

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里面的完整回调引用jqXHR对象吗?
  • @inf3rno,很抱歉,但我是这种编程风格的新手。为什么原型会更快?
  • 因为它是一个核心的js特性,所以它是在你的js引擎中实现的,例如在v8 by chrome。
  • 它会更快,因为你的“类”的所有实例都将共享相同的内存。
  • @inf3rno,我假设在主 myClass 函数中我可以声明可以在所有原型中引用的变量?我可以在原型中通过 var name 调用它们对吗?
【解决方案2】:

匿名回调函数中的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));

【讨论】:

  • 在这些情况下,我们通常会调用bind来更改范围,使用thatself等...很长时间不建议使用。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多