面试题:承诺链是如何实现的?我当时没反应过来。面试官很有耐心说jquery也是有链的。你看过jquery的源代码吗?它的链是怎么写的?我还是不知道。我没有通过面试。这个知识点经常被我回忆起来。现在我有时间写一篇文章。答案是:回到这个,让我们从一个例子开始:varperson={name:'johan',age:28,sayName:function(){console.log('mynameis'+this.name)},sayAge:function(){console.log('myageis'+this.age)}}命名一个对象,它有两个方法sayName和sayAge,如果我想表达person.sayName().sayAge()怎么办像这样?怎么做,在方法sayName和sayAge中返回this,即varperson={name:'johan',age:28,sayName:function(){console.log('mynameis'+this.name)returnthis;},sayAge:function(){console.log('我的年龄是'+this.age)returnthis;}}意思是调用sayName和sayAge方法后,返回给调用者,即例子person.sayName(),person调用sayName,调用后返回值还是person。所以它可以继续调用一个链中的sayAge,因为它仍然代表personPromise中的链。Promise本身没有链,但是Promise的实例对象中有链functionMyPromise(executor){}MyPromise.prototype.then=function(onFulfilled,onRejected){returnnewPromise((resolve,reject)=>{...})}当你使用Promise时,一般是这样使用的:letpromise=newPromise((resolve,reject)=>{setTimeout(resolve,1000)})promise.then(()=>{console.log('1s后显示')})如果添加链式promise.then(()=>{console.log('1s后显示,第一个')}).then(()=>{console.log('1s后显示,第二个')})所以很明显,每次调用then,都会返回一个实例对象(returnnewPromise)Jquery中的链源码内容太多,拿core.js中的代码例如jQuery.fn=jQuery.prototype={//当前使用的jQuery版本jquery:version,constructor:jQuery,//jQuery对象的默认长度为0length:0,toArray:function(){返回slice.call(this);},//获取匹配元素集中的第N个元素OR//获取整个匹配元素集作为一个干净的数组get:function(num){//返回干净数组中的所有元素if(num==null){returnslice.call(this);}//只返回集合中的一个元素returnnum<0?这个[num+this.length]:这个[num];},//获取一个元素数组并将其压入堆栈//(返回新的匹配元素集)pushStack:function(elems){//构建一个新的jQuery匹配元素集varret=jQuery.merge(this.构造函数(),元素);//将旧对象添加到堆栈中(作为参考)ret.prevObject=this;//返回新形成的元素集合returnret;},//为匹配集中的每个元素执行回调。each:function(callback){returnjQuery.each(this,callback);}},map:function(callback){returnthis.pushStack(jQuery.map(this,function(elem,i){returncallback.call(elem,i,elem);});},slice:function(){returnthis.pushStack(slice.apply(this,arguments));},首先:function(){returnthis.eq(0);},最后:function(){returnthis.eq(-1);},even:function(){returnthis.pushStack(jQuery.grep(this,function(_elem,i){return(i+1)%2;}));},奇数:function(){返回这个。pushStack(jQuery.grep(this,function(_elem,i){returni%2;}));},eq:function(i){varlen=this.length,j=+i+(i<0?len:0);返回this.pushStack(j>=0&&j
