JS 函数的 call、apply 及 bind 方法
一、call() 方法调用 call() 方法会立即执行目标函数,同时改变函数内部 this 的指向。this 指向由方法的第一个参数决定,后面逐个列举的任意个参数将作为目标函数的参数一一对应传入。 /* 正常模式 */let obj = { sum(a, b) { console.log(this) return a + b }}// 执行 sum 函数的 apply、bind 方法,打印的 this 同下obj.sum.call() // 打印 windowobj.sum.call(undefined, 1, 2) // 打印 windowobj.sum.call(null, 1, 2) // 打印 window/* 严格模式 */'use strict'// 执行 sum 函数的 apply、bind 方法,打印的 this 同下obj.sum.call() // 打印 undefinedobj.sum.call(undefined, 1, 2) // 打印 undefinedobj.sum.call(null, 1, 2) // 打印 null
1、call()方法的模拟实现关键点: myCall() 方法被添加在 Function 原型对象上,目标函数调用该方法时,myCall() 方法内部的 this 将指向目标函数。 - 将目标函数作为 context 对象的方法来执行,由此目标函数内部的 this 将指向 context 对象。
- 从 context 对象中删除目标函数
- 使用扩展运算符
... 处理传入目标函数的参数 call()、apply()、bind() 方法的模拟实现中,对于不传第一个参数或者传递 undefined、null 时,这里在 JS 正常模式和严格模式下做了统一处理,即目标函数内部的 this 均指向 window 对象。
代码如下: Function.prototype.myCall = function (context, ...args) { if (context === undefined || context === null) { context = window } // 下面这行为核心代码 context.fn = this const result = context.fn(...args) delete context.fn return result}let obj1 = { basicNum: 1, sum(a, b) { console.log(this) return this.basicNum + a + b }}let obj2 = { basicNum: 9}console.log(obj1.sum.call(obj2, 2, 3)) // 14console.log(obj1.sum.myCall(obj2, 2, 3)) // 14
二、apply() 方法调用 apply() 方法会立即执行目标函数,同时改变函数内部 this 的指向。this 指向由方法的第一个参数决定,第二个参数是一个参数数组或 arguments 对象,各数组元素或 arguments 对象表示的各参数将作为目标函数的参数一一对应传入。
1、apply()方法的模拟实现
关键点: myApply() 方法被添加在 Function 原型对象上,目标函数调用该方法时,myApply() 方法内部的 this 将指向目标函数。 - 将目标函数作为 context 对象的方法来执行,由此目标函数内部的 this 将指向 context 对象。
- 从 context 对象中删除目标函数
- 使用扩展运算符
... 处理传入目标函数的参数 代码如下: Function.prototype.myApply = function (context, args) { if (context === undefined || context === null) { context = window } // 下面这行为核心代码 context.fn = this const result = context.fn(...args) delete context.fn return result}console.log(obj1.sum.apply(obj2, [2, 3])) // 14console.log(obj1.sum.myApply(obj2, [2, 3])) // 14
三、bind() 方法 |