襄阳做网站的,山东网站开发学校,永久免费空间网站,制定 网站改版优化方案0、call、apply、bind的区别 bind#xff0c;call#xff0c;apply的作用都是用来改变this指向的 call方法 call方法的第一个参数是this的指向 后面传入的是一个参数列表#xff08;注意和apply传参的区别#xff09;。当一个参数为null或undefined的时候#xff0c;函数中…0、call、apply、bind的区别 bindcallapply的作用都是用来改变this指向的 call方法 call方法的第一个参数是this的指向 后面传入的是一个参数列表注意和apply传参的区别。当一个参数为null或undefined的时候函数中的this默认指向window(在浏览器中)和apply一样call也只是临时改变一次this指向并立即执行。 apply方法使用apply方法改变this指向后原函数会立即执行且此方法只是临时改变thi指向一次。 apply接受两个参数 第一个参数是this的指向 第二个参数是函数接受的参数以数组的形式传入且当第一个参数为null、undefined的时候函数中的this默认指向window(在浏览器中) 3. bind方法 bind方法和call很相似 第一参数也是this的指向 后面传入的也是一个参数列表(但是这个参数列表可以分多次传入call则必须一次性传入所有参数)但是它改变this指向后不会立即执行而是返回一个永久改变this指向的函数。 一、call函数的实现 // 给所有的函数添加一个myCall方法
Function.prototype.myCall function (thisArg, ...args) {// 1. 获取需要被执行的函数var fn this// 对thisArg转成对象类型防止它传入的是非对象类型的参数thisArg thisArg ? Object(thisArg) : window// 2.为调用myCall的函数绑定this利用了js的隐式绑定thisArg.fn fn// 3.调用需要被执行的函数const result thisArg.fn(...args)delete thisArg.fn// 4.将函数的调用结果返回return result
}const result sum.myCall(aaa, 10, 20)
console.log(result)function sum(num1, num2) {console.log(sum函数被执行了, this)return num1 num2
}// const result sum.call(aaa, 20, 30)
// console.log(result)
二、apply函数的实现 Function.prototype.myApply function (thisArg, argArr) {// 1. 获取调用myApply的函数var fn this// 2. 将thisArg转成对象类型否则后续无法通过thisArg.fn绑定this// 且若thisArg没有传值则让this绑定为windowthisArg (thisArg ! null thisArg ! undefined) ? Object(thisArg) : windowthisArg.fn fn// 3. 对argArr进行处理确保它有传值并且为数组// 否则后续通过...argArr解构会报错因为如果argArr不传值时为undefined...undefined解构就会报错argArr argArr ? argArr : []// 4. 执行函数const result thisArg.fn(...argArr)delete thisArg.fn// 5. 将函数执行结果返回return result
}
function sum(num1, num2) {console.log(this, num1, num2)return num1 num2
}
const result1 sum.myApply(aaa, [10, 20])
console.log(result1)
const result2 sum.myApply(0)
console.log(result2)
sum.apply(aaa, [10, 20])
sum.apply(0)
三、bind函数的实现
bind方法和call很相似 第一参数也是this的指向 后面传入的也是一个参数列表(但是这个参数列表可以分多次传入call则必须一次性传入所有参数)但是它改变this指向后不会立即执行而是返回一个永久改变this指向的函数。
Function.prototype.myBind function (thisArg, ...argArr) {// 1.获取道真实需要调用的函数var fn this// 2.处理thisArg不传值的情况不传值则默认函数里的this绑定window传了值则还需要确保它为对象类型否则后续thisArg.fn fn会报错thisArg (thisArg ! null thisArg ! undefined) ? Object(thisArg) : windowvar proxyFn function (...args) {// 3.绑定this(这里用了js的隐式绑定)thisArg.fn fn// 4.将函数传入的剩余参数进行合并用于实现bind函数的第二个参数列表可以分多次传入const finalArgArr [...argArr, ...args]// 5.调用函数const result thisArg.fn(...finalArgArr)delete thisArg.fn// 6.将函数执行结果返回return result}return proxyFn
}
function sum(num1, num2) {console.log(this, num1, num2)return num1 num2
}
const newSum sum.myBind(aaa, 10, 20) // 参数列表可以分多次传入
const result newSum(30, 40) // 参数列表可以分多次传入
console.log(result)