bind、call、apply的特点

1、bind 可以改变绑定this指向,板顶参数

let obj = {
  name: "jim",
};

function fn() {
  this.say="说话";
  console.log(this);
}


/***
 * 1、bind 的方法可以绑定this指向, 绑定参数
 * 2、返回一个绑定后的函数 (高阶函数)
 * 3、如果绑定的函数被new了,当前函数的this 就是当前的实例
 * 4、new出来的结果,可以找到原有类的原型
 */

Function.prototype.bind = function (context) {
  let that = this;
  let bindArgs = Array.prototype.slice.call(arguments, 1); //[]
  function Fn(){}   //Object.create() 的原理
  function fBound() {
    let args = Array.prototype.slice.call(arguments, 1);
    return that.apply(
      this instanceof fBound ? this : context,
      bindArgs.concat(args)
    );
  }
  Fn.prototype=this.prototype;
  fBound.prototype=new Fn();
  return fBound;
};

fn.prototype.flag='哺乳类';
let bindFn = fn.bind(obj,'猫');
let instance =new bindFn(9);
console.log(instance.flag);

2、 call 传入的数组,改变this指向

function fn1() {
  console.log(1);
}

function fn2() {
  console.log(2);
}
fn1.call(); //输出fn1
fn1.call.call(fn2); //输出fn2

Function.prototype.call = function (context) {
  context = context ? Object(context) : window;
  context.fn = this;
  let args = [];
  for (let i = 1; i < arguments.length; i++) {
    args.push("arguments[" + i + "]");
  }
  // 利用数组的toString的特性
  let r = eval("context.fn(" + args + ")");
  delete context.fn;
  return r;
};

// 如果多个call,会让call方法执行,并且会把call中的this改变成fn2;
// call 传入的是数组,apply传入的是一个个的字符串。

3、apply 传入的是字符串,改变this指向

function fn1() {
  console.log(this,arguments);
}

Function.prototype.apply = function (context,args) {
  context = context ? Object(context) : window;
  context.fn = this;
  if(!args){
      return context.fn();
  }
  for (let i = 1; i < arguments.length; i++) {
    args.push("arguments[" + i + "]");
  }
  // 利用数组的toString的特性
  let r = eval("context.fn(" + args + ")");
  delete context.fn;
  return r;
};

fn1.apply('hello',[1,2,3,4]);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vues

刚好遇见你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值