JavaScript中的apply(),call(),bind()的使用

这三个方法都是用来改变函数里面的this指向的
1.call() /apply()
call 与 apply 都是用于将对象绑定到 this,只是在传递参数上有所不同。apply 用数组传参,call 需要分别传参,这两个方法都会立即执行

function User(name,age) {
 this.name = name;
 this.age=age

}
let xxx={};
//第一个参数是要设置的指针指向,这里是让User的this指向xxx
//第二个参数是 User()中要传入的参数
User.call(xxx,'xiaozhuo',22)
//User.apply(xxx,['xiaozhuo',22])
console.log(xxx);//{name: 'xiaozhuo', age: 22}

案例:实现构造函数属性继承

function Request() {
  this.get = function(params = {}) {
    //组合请求参数
    let option = Object.keys(params)
      .map(i => i + "=" + params[i])
      .join("&");

    return `获取数据 API:${this.url}?${option}`;
  };
}
function Lesson() {
  this.url = "lesson/index";
  Request.call(this);
  
}
let js = new Lesson();
console.log(
  js.get({
    row: 20
  })
  )//获取数据 API:lesson/index?row=20

2.bind()
bind()是将函数绑定到某个对象,比如 a.bind(hd) 可以理解为将 a 函数绑定到 hd 对象上即 hd.a()。

  • 与 call/apply 不同 bind 不会立即执行
  • bind 是复制函数形为会返回新函数

bind 是复制函数行为

function hd(a, b) {
  return this.f + a + b;
}

let a={f:1}
//使用bind会生成新函数
let newFunc = hd.bind(a);//这里newFunc 的指向就指向a了
console.log(newFunc(2,3));//6

let newFunc = hd.bind(a,3,6);//这里newFunc 的指向就指向a了
console.log(newFunc());//10

let newFunc = hd.bind(a,3,6);//这里newFunc 的指向就指向a了
console.log(newFunc(2,5));//10 还是会采用之前传入的参数

let newFunc = hd.bind(a,3);//这里newFunc 的指向就指向a了
console.log(newFunc(5));//9

要注意bind()里面的参数传入

function hd(a, b) {
  return this.f + a + b;
}

let a={f:1}
let newFunc = hd.bind(a,3,6);//这里newFunc 的指向就指向a了
console.log(newFunc(2,5));//10 还是会采用之前传入的参数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值