gpt4 book ai didi

javascript - $.Deferred().promise 与 $.get().promise

转载 作者:行者123 更新时间:2023-12-03 07:46:09 24 4
gpt4 key购买 nike

我正在尝试以下代码:

var x=$.get();
x.promise();

var y=new $.Deferred();
y.promise();

用于比较$.Deferred().promise 和 $.get().promise在这两种情况( x.promise() 和 y.promise() )中,Chrome 调试器都会将我引导至 jQuery 源代码的同一行:

promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}

但是,x.promise==y.promise 返回false!!! 为什么?我无法给出解释...

我需要一些帮助。谢谢

最佳答案

伊利亚斯这是因为对象 defer 和对象 promise 不是同一个实例,即使它们是从相同的代码创建的......每次调用 jQuery.Deferred 方法都会创建新对象。

Deferred: function( func ) {
// notice, these define is in the Deferred method, every time is whole new object
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
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();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};

关于javascript - $.Deferred().promise 与 $.get().promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com