时间:2022-12-17 09:50:29 | 栏目:JavaScript代码 | 点击:次
1、相同点
2、区别
/* 正常模式 */
let obj = {
sum(a, b) {
console.log(this)
return a + b
}
}
// 执行 sum 函数的 apply、bind 方法,打印的 this 同下
obj.sum.call() // 打印 window
obj.sum.call(undefined, 1, 2) // 打印 window
obj.sum.call(null, 1, 2) // 打印 window
/* 严格模式 */ 'use strict' // 执行 sum 函数的 apply、bind 方法,打印的 this 同下 obj.sum.call() // 打印 undefined obj.sum.call(undefined, 1, 2) // 打印 undefined obj.sum.call(null, 1, 2) // 打印 null
1、关键点
2、call()、apply()、bind() 方法的模拟实现中,对于不传第一个参数或者传递 undefined、null 时,这里在 JS 正常模式和严格模式下做了统一处理,即目标函数内部的 this 均指向 window 对象。
3、代码如下
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)) // 14
console.log(obj1.sum.myCall(obj2, 2, 3)) // 14
调用 apply() 方法会立即执行目标函数,同时改变函数内部 this 的指向。this 指向由方法的第一个参数决定,第二个参数是一个参数数组或 arguments 对象,各数组元素或 arguments 对象表示的各参数将作为目标函数的参数一一对应传入。
1、关键点
2、代码如下
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])) // 14
console.log(obj1.sum.myApply(obj2, [2, 3])) // 14
1、关键点
2、代码如下
Function.prototype.myBind = function (context, ...initArgs) {
if (context === undefined || context === null) {
context = window
}
// 缓存 this 值
const _this = this
return function (...args) {
// 下面这行为核心代码
context.fn = _this
const result = context.fn(...initArgs, ...args)
delete context.fn
return result
}
}
console.log(obj1.sum.bind(obj2, 2)(3)) // 14
console.log(obj1.sum.myBind(obj2, 2)(3)) // 14
相关知识点