Function.prototype.bind()

一、创建绑定函数

  场景:将一个方法从对象中取出调用,期望this指向原来的对象。

var a=30;

var obj={
     a:20,
     getA:function(){
        console.log(this.a)    
  }            
}

obj.getA() //20

var newGetA=obj.getA;
newGetA(); //30

解决方法: var anotherGetA=obj.getA.bind(obj); anotherGetA(); //20

二、偏函数

使一个函数拥有预设的初始参数;

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

const add1 = add.bind(null, 10);
const result = add1(20, 8);
console.log(result) //38

猜你喜欢

转载自www.cnblogs.com/EllenChen/p/12375303.html