总结 1、相同点 都能够改变目标函数执行时内部 this 的指向 方法的第一个参数用于指定函数执行时内部的 this 值 支持向目标函数传递任意个参数
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
相关知识点
到此这篇关于JavaScript函数之call、apply以及bind方法案例详解的文章就介绍到这了,更多相关JavaScript函数之call、apply以及bind方法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: JavaScript函数之call、apply以及bind方法案例详解
本文链接: https://www.lsjlt.com/news/134001.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0