先了解下bind call apply 的注意点
  • bind 需要手动调用 第一个参数 this 要指向的对象,后面是 散列的参数
  • call 不需要手动调用 第一个参数 this 要指向的对象,后面是 散列的参数
  • apply 不需要手动调用 第一个参数 this 要指向的对象,后面是 数组参数
看下具体代码
  • bind
function fn(a,b) {
    console.log(a,b)
    console.log(this,'this')
}
fn(1,2)
// 1 2
// Window  'this'
let obj = {
    name:'wg',
    age:18
}
let res = fn.bind(obj,2,3)  // fn的this指向obj
res()
// 2 3
// {name: 'wg', age: 18} 'this'
  • call
function fn(a,b) {
    console.log(a,b)
    console.log(this,'this')
}
fn(1,2)
// 1 2
// Window  'this'
let obj = {
    name:'wg',
    age:18
}
fn.call(obj,2,3) // fn的this指向obj
// 2 3
// {name: 'wg', age: 18} 'this'
  • apply
function fn(a,b) {
    console.log(a,b)
    console.log(this,'this')
}
fn(1,2)
// 1 2
// Window  'this'
let obj = {
    name:'wg',
    age:18
}
fn.apply(obj,[2,3]) // fn的this指向obj
// 2 3
// {name: 'wg', age: 18} 'this'