javaScript 基础知识汇总 (十一)

1、柯里化和偏函数

  偏函数

  假如一个函数有两个参数,然后第一个参数我们调用的时候是确定的,那么我门就可以创建一个偏函数来简化参数传递的问题

  示例

  function mul(a,b){

    return a * b;

  }

  let double = mul.bind(null,2);

  alert(double(3));//=mul(2,3) =6

  let triple = mul.bind(null,3); 

  alert(triple(3));// = mull(3,3)=9

  无上下文使用偏函数

 1 function partial(func, ...argsBound) {
 2   return function(...args) { // (*)
 3     return func.call(this, ...argsBound, ...args);
 4   }
 5 }
 6 
 7 // 用法:
 8 let user = {
 9   firstName: "John",
10   say(time, phrase) {
11     alert(`[${time}] ${this.firstName}: ${phrase}!`);
12   }
13 };
14 
15 // 添加一个偏函数方法,现在 say 这个函数可以作为第一个函数
16 user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes());
17 
18 user.sayNow("Hello");
19 // 结果就像这样:
20 // [10:00] John: Hello!
21 
22 
23 partial(func[, arg1, arg2...]) 调用的结果是一个基于 func 的封装函数,以及:
24 和它传入的函数一致的 this (对于 user.sayNow 调用是 user)
25 然后传入 ...argsBound —— 来自偏函数调用传入的参数("10:00"26 然后传入 ...args —— 传入封装函数的参数(Hello)

  柯里化

  个人理解:多个函数的嵌套

function curry(func) {
  return function(a) {
    return function(b) {
      return func(a, b);
    };
  };
}

// 用法
function sum(a, b) {
  return a + b;
}

let carriedSum = curry(sum);

alert( carriedSum(1)(2) ); // 3

  柯里化是将 f(a,b,c) 可以被以 f(a)(b)(c) 的形式被调用的转化。JavaScript 实现版本通常保留函数被正常调用和在参数数量不够的情况下返回偏函数这两个特性

2、箭头函数

  箭头功能没有“this”

  箭头函数没有this。如果访问this,则从外部获取  

 1 let group = {
 2   title: "Our Group",
 3   students: ["John", "Pete", "Alice"],
 4 
 5   showList() {
 6     this.students.forEach(
 7       student => alert(this.title + ': ' + student)
 8     );
 9   }
10 };
11 
12 group.showList();

  但是foreach内部,如果封装了一个函数,就会丢失this

 1 let group = {
 2   title: "Our Group",
 3   students: ["John", "Pete", "Alice"],
 4 
 5   showList() {
 6     this.students.forEach(function(student) {
 7       // Error: Cannot read property 'title' of undefined
 8       alert(this.title + ': ' + student)
 9     });
10   }
11 };
12 
13 group.showList();

   箭头函数没有“arguments”(参数)

  箭头函数

 1 function defer(f, ms) {
 2   return function() {
 3     setTimeout(() => f.apply(this, arguments), ms)
 4   };
 5 }
 6 
 7 function sayHi(who) {
 8   alert('Hello, ' + who);
 9 }
10 
11 let sayHiDeferred = defer(sayHi, 2000);
12 sayHiDeferred("John"); // 2 秒后打印 Hello, John

  无箭头函数

1 function defer(f, ms) {
2   return function(...args) {
3     let ctx = this;
4     setTimeout(function() {
5       return f.apply(ctx, args);
6     }, ms);
7   };
8 }

猜你喜欢

转载自www.cnblogs.com/xiaoqiyaozou/p/11490990.html