问答详情
源自:5-6 Deferred源码剖析(上)

为什么这个newDefer直接用了,前面也没有定义啊?

then: function( /* fnDone, fnFail, fnProgress */ ) {
                    var fns = arguments;
                    return jQuery.Deferred(function( newDefer ) {    
//-------------- newDefer 也为什么直接就有了resolve,done方法呢?              
                    
                        jQuery.each( tuples, function( i, tuple ) {
                            var action = tuple[ 0 ],
                                fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
                            // deferred[ done | fail | progress ] for forwarding actions to newDefer
                            deferred[ tuple[1] ](function() {
                                var returned = fn && fn.apply( this, arguments );
                                if ( returned && jQuery.isFunction( returned.promise ) ) {
                                    returned.promise()
                                        .done( newDefer.resolve )
                                        .fail( newDefer.reject )
                                        .progress( newDefer.notify );
                                } else {
                                    newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
                                }
                            });
                        });
                        fns = null;
                    }).promise();
                }


提问者:夜晚的一场梦 2016-10-12 20:26

个回答

  • 夜晚的一场梦
    2016-10-12 20:36:56

    懂了,汗,自己突然就想通了,原因在于这行代码:

    if ( func ) {
                func.call( deferred, deferred );
            }

    call里面第二个deferred对象作为参数穿进去了,正好对应

     return jQuery.Deferred(function( newDefer ) {

    这个newDefer, 这样就对啦,哈哈