在看函数的链式调用想到一个问题,那就是链式调用都用this返回当前对象。如果要返回当前对象的值,那么必须自己去取。如以下:
// 随便复制过来的,侵删.
function ClassA(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
ClassA.prototype = {
method1 : function(p1){
this.prop1 = p1;
return this;
},
method2 : function(p2){
this.prop2 = p2;
return this;
},
method3 : function(p3){
this.prop3 = p3;
return this;
}
}
var obj = new ClassA();
obj.method1(1).method2(2).method3(3); // obj -> prop1=1,prop2=2,prop3=3
那么es6中的filter和map是如何实现的?这两个方法都可以链式调用,而且也能返回操作结果。比如:
let arr = [
{ name: "王小二", id: "12323", sex: "0" },
{ name: "李虎", id: "12332", sex: "1" },
{ name: "王贺", id: "12323", sex: "0" },
];
let newArr = arr.filter((item) => item.sex === "0").map((item) => ({ name: item.name, id: item.id }));
有没有大佬能写一个例子说明一下?谢谢。
第一,这两个方法是 ES5 的,不是 ES6 的(倒是你用的
let
关键字和箭头函数这俩特性是 ES6 的)。第二,这俩方法只是个会返回一个新数组的方法,严格意义上来说并不是链式调用,链式调用得返回自身。
可以看下 polyfill: