call,apply,bind都是用来改变this指向的
call:通过一个一个传参,返回的是函数的执行结果
apply:以一个数组的形式传参,返回的也是函数的执行结果
bind:通过一个一个传参,返回的是一个函数,首要手动调用。
call方法
首先,我们知道call是用来改变this指向的,它可以给一个函数一个指定的this值,并且可以传参数。
let a = {
value: 1
}
function getValue(name, age) {
console.log(name)
console.log(age)
console.log(this.value)
}
// getValue.call(a, 'lss', '22') => a.fn = getValue
getValue.call(a, 'lss', 22)
console.log(a)
实现的思想就是:
给obj添加fn,赋值一个函数
调用obj.fn,再在obj上删除这个函数。
function myCall(context) {
var context = context || window
// 给 context 添加一个属性
context.fn = this
// 将 context 后面的参数取出来
var args = [...arguments].slice(1)
var result = context.fn(...args)
// 删除 fn
delete context.fn
return result
}
//在函数Function的原型上添加这个方法,供函数的其他实例调用
Function.prototype.myCall = myCall
getValue.myCall(a, 'hyd', 23)
apply方法
apply跟call一样,只不过在于传参的不同,apply是以数组的形式进行传参的。
let a = {
value: 1
}
function getValue(name, age) {
console.log(name)
console.log(age)
console.log(this.value)
}
getValue.apply(a, ['lss', 22])
实现思想跟call一样
Function.prototype.myApply = function (context) {
var context = context || window
context.fn = this
var result
// 需要判断是否存储第二个参数
// 如果存在,就将第二个参数展开
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
getValue.myApply(a, ['hyd', 23])
bind跟call和apply差不多,只不过bind不会立即调用函数会返回一个匿名函数,需要手动调用函数。
let a = {
value: 1
}
function getValue(name, age) {
console.log(name)
console.log(age)
console.log(this.value)
}
getValue.bind(a, 'lss', 22)()
Function.prototype.myBind = function (context) {
var _this = this
var args = [...arguments].slice(1)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
getValue.myBind(a, 'hyd', 23)()
总结
归根到底,我们实现的思想很简单,我们改变this指向,其实可以理解为就是把这个函数添加到obj上,然后执行完删除。(若有不对,望指出)