网站seo优化如何做,抽奖网站怎么制作,wordpress打教程,网站分站加盟链式调用在JavaScript很常见#xff0c;比如jQuery、Promise和其它的插件等#xff0c;都是使用的链式调用。链式调用可以让我们在进行连续操作时#xff0c;写出更简洁的代码。
链式调用它允许你在单个对象上连续调用多个方法#xff0c;每个方法的返回值都是调用它的那个…链式调用在JavaScript很常见比如jQuery、Promise和其它的插件等都是使用的链式调用。链式调用可以让我们在进行连续操作时写出更简洁的代码。
链式调用它允许你在单个对象上连续调用多个方法每个方法的返回值都是调用它的那个对象本身或者是另一个可以进行链式调用的对象。这种编程风格可以使代码更加简洁和易读。
1使用对象进行链式调用 let obj{start(){console.log(这是测试1)return this},center(){console.log(这是测试2)return this},end(){console.log(这是测试3)return this}}obj.start().center().end()//这是测试1//这是测试2//这是测试3
1使用函数进行链式调用 function Person(name,age) {this.namenamethis.ageage}//在原型上添加方法Person.prototype{start(){console.log(这是测试1)return this},center(){console.log(这是测试2)return this},end(){console.log(这是测试3)return this}}let P1new Person(张三,18)P1.start().center().end()//这是测试1//这是测试2//这是测试3
3,类似jquery中的链式调用
!DOCTYPE html
html langen
headmeta charsetUTF-8title函数链式调用/titlestyle#doms{width:100px;height: 100px;border: 1px solid red;}/style
/head
body
div iddoms/div
scriptfunction selectContent(selector) {return{el:document.querySelector(selector),height:function(h){this.el.style.heighthreturn this},width:function(w){this.el.style.widthwconsole.log(this)return this}}}let dom selectContent(#doms)//dom.height(220px)dom.height(220px).width(220px)
/script
/body
/html
4,遍历数组进行链式调用 function f1() {console.log(f1)}function f2() {console.log(f2)}function f3() {console.log(f3)}let fns[f1,f2,f3]let test (fns){//循环单个执行fns.forEach(fn{fn();})}test(fns)//f1//f2//f3
这种调用方式比较简单
实现方式不止这几种像是递归或闭包也都是可以的。