一、call()
- 语法:通过
call()
调用函数,fn.call(obj,...args)
- 调用函数的时候,可以设置obj,改变this指向
- 如果obj是null或undefined,this指向window
- 后面的参数是若干个,数量是可变的
function func(a, b) {
console.log('func', this, a, b);
}
func();
func.call([1, 2, 3], 122, 33);
(function () {
console.log(this);
}).call(100)
var obj = {
name: 'obj',
getInfo: function () {
console.log(this);
}
}
obj.getInfo()
obj.getInfo.call('hello')
二、apply()
- 通过
apply()
调用函数 - 调用函数的时候,可以设置函数内部的
this
- 除了this只有一个参数,并且是数组,其中的数组元素将作为单独的参数传给fun函数。和
call()
唯一的区别
function func(a, b) {
console.log('func', this, a, b);
}
func.apply({ name: 'xxx' }, [12, 'ss'])
三、bind()
- 返回一个新的函数,需要手动调用
- bind创建时设置this,也可以设置一个固定参数
- 调用新函数时,设置参数
function func(a, b) {
console.log('func', this, a, b);
}
var fn1 = func.bind([2, 3])
fn1('q', 'w');
var user = { name: 'xxx' }
user.getInfo = func.bind(100, 'qwe');
user.getInfo()
四、手写call、apply、bind函数
function myCall(fn, thisarg, ...args) {
if (thisarg == null || thisarg == undefined) {
return fn(...args)
}
thisarg.tempFn = fn
const result = thisarg.tempFn(...args)
delete thisarg.tempFn
return result
}
function myApply(fn, thisarg, args) {
if (thisarg == null || thisarg == undefined) {
return fn(args)
}
thisarg.tempFn = fn
let result
if (!args) {
result = thisarg.tempFn()
} else {
result = thisarg.tempFn(...args)
}
delete thisarg.tempFn
return result
}
function myBind(fn, thisarg, ...args) {
return function (...args2) {
return myCall(fn, thisarg, ...args, ...args2)
}
}
function func(a, b) {
console.log(this, a, b);
}
myCall(func, [1, 2])
myApply(func, [1, 2])
let res = myBind(func, [1, 2], 'w')
console.log(res(1));