很多时候,都会使用到链式调用,这类使用一般都是框架封装好的,一个·方法连一个方法,简洁又高效,其本质就是在方法执行完之后,返回当前this,也就是说返回对象本身;
上代码
<script>
//链式调用
const vw={
data:0,
insert(n,fn){
this.data=n;
fn(this.data);
return this;
},
add(fn){
if( typeof this.data !='number'){
fn(this.data);
return this;
}
this.data++;
fn(this.data);
return this;
},
subtract(fn){
if( typeof this.data !='number'){
fn(this.data);
return this;
}
this.data--;
fn(this.data);
return this;
},
ride(fn){
if( typeof this.data !='number'){
fn(this.data);
return this;
}
this.data=this.data*this.data;
fn(this.data);
return this;
},
divide(n){
if( typeof this.data !='number'){
fn(this.data);
return this;
}
this.data=this.data/Number(n);
return this;
}
}
function App(vw){
var obj={};
for(var key in vw){
obj[key]=vw[key];
App(vw[key]);
}
return obj;
}
var arr=[1,2,3,4,5]
let p=new App(vw);
p.add((data)=>{
console.log(data);
}).subtract(data=>{
console.log(data);
}).ride(data=>{
console.log(data);
}).add(data=>{
console.log(data);
}).insert(arr,(data)=>{
console.log(data);
}).add(data=>{
console.log(add);
});
</script>
</script>
效果