【问题标题】:javascript chainning return this from callbackjavascript 链接从回调返回 this
【发布时间】:2012-12-24 21:20:02
【问题描述】:

我试图从回调中获取返回 this,但我总是未定义。

这里是截图

create: function(currentView, data){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast", function(){
        return itsMe;                                                 
    });
},

var l = list().create(currentView); //need teh return that i can use chaining

var l 现在是未定义的,如果我使用带有回调的fadeIn... 如果我不在回调中使用fadeIn,它会返回obj

有人知道为什么吗?

【问题讨论】:

  • 因为回调将值返回到它被调用的位置,即.fadeIn 内部的某个位置。对create函数没有影响。

标签: javascript callback return chaining


【解决方案1】:

@Felix Kling 说的是正确的,你没有返回任何东西。如果你想返回itsMe,你需要这样做:

create: function(currentView, data){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast");
    return itsMe;    
}

如果您想要链接,这应该足够了。

如果您想在淡出完成时获得对itsMe 的引用,则需要传递您自己的回调:

create: function(currentView, data, callback){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast", function(){ 
        callback(itsMe);
    });  
}


list().create(function (that) {
    console.log("fade out complete");
    console.log("itsMe is", that);
});

如果你想有一个链接模式,当淡出完成时将执行链中的下一个函数,你需要传递的不是this的引用,而是一个可以排队命令的对象,实现每个依次命令。

【讨论】:

    【解决方案2】:

    你需要在create()函数中返回对象,它目前没有返回任何东西:

    create: function(currentView, data){
        var itsMe = this; 
        this.thumbsWrapper = this.templates.wrapper().hide();
        currentView.append(this.thumbsWrapper);
        this.thumbsWrapper.fadeIn("fast", function(){
            return itsMe;  //<--- this isn't going anywhere because you don't capture it                                               
        });
        return itsMe; //<------ return the object
    },
    

    【讨论】:

    • 还要注意,由于动画函数的异步特性,这个函数会尽快返回,即在动画中加入淡入淡出的动画后立即返回排队。
    • @MattiasBuelens 没错,但没关系,因为他没有做任何事情,也没有在 fadeIn 完整调用中修改 itsMe
    • 同意,我只是注意到,因为不清楚何时 OP 期望create 函数返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2016-07-01
    • 2011-09-18
    • 2018-06-27
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多