柯里化实现方案 && 形参 && this指向

1 柯里化实现方案

function sum(a, b, c, d) { return a + b + c + d; }
console.log('===>apply', sum.apply(this, ([1, 2, 3, 4]))); // ===>apply 10 // this指向undefined
console.log('===>', sum([1, 2, 3, 4])); // ===> 1,2,3,4undefinedundefinedundefined
function curry(func) {
  return function curried(...args) {
    console.log('===>args', args); // ===>args [ 1, 2, 3 ]
    console.log('===>func', func); // ===>func [Function: sum]
    console.log('===>func.length', func.length); // ===>func.length 4 // 表示func的形参个数
    if (args.length >= func.length) {
      // node环境下是global;浏览器环境中是window;(非严格模式下,this指向全局对象;严格模式下,this指向undefined或者实际调用者)
      return func.apply(this, args);
    } else {
      return function (...args2) {
        return curried.apply(this, args.concat(args2));
      };
    }
  }
}

function sum(a, b, c, d) { return a + b + c + d; }

let currriedSum = curry(sum);
console.log(currriedSum(1, 2, 3, 4)); // 10
console.log(currriedSum(1, 2)(3, 4)); // 10 对第一个参数的柯里化
console.log(currriedSum(1)(2)(3)(4)); // 10 全柯里化

2 形参

箭头函数只支持…args

const a = new Array();
Array.prototype.cy = function() {
  console.log('===>arguments', [...arguments]);
  // ===>arguments [ '111' ]
};
Array.prototype.cy2 = function(...args) {
  console.log('===>args', [...args]);
  // ===>args [ [ 1, 2, 3 ] ]
};

a.cy('111');
a.cy2([1, 2, 3]);
const b = new Array();
Array.prototype.cy = (...args) => {
  console.log('===>箭头函数', [...args]);
  // ===>箭头函数 [ '111' ]
}

b.cy('111');

3 this指向

箭头函数的this指向有点特别,它总是指向最近的外层作用域中的this所指对象;
块级作用域,全局作用域,函数作用域

const obj = {
  normalFunc: function() {
    console.log(this); // 输出 obj
  },
  arrowFunc: () => {
    console.log(this); // 输出全局对象或 undefined(取决于环境是否为严格模式)
  }
};

obj.normalFunc(); // 正常绑定到 obj
obj.arrowFunc(); // 不绑定到 obj
var a = 11;
function test2() {
  this.a = 22;
  let b = () => { console.log(this.a) }
  b();
}
var x = new test2(); //22

它会继承外层(词法)作用域中的 this 值,而不能通过传统的 call、apply 或 bind 方法来改变。

const value = "outer this value";

const arrowFunc = () => {
  console.log(this.value);
};

const anotherObj = { value: "another this value" };

// 尝试更改 arrowFunc 的 this 指向
arrowFunc.call(anotherObj); // undefined
const value = "outer this value";

const arrowFunc = function () {
  console.log(this.value);
};

const anotherObj = { value: "another this value" };

// 尝试更改 arrowFunc 的 this 指向
arrowFunc.call(anotherObj); // another this value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值