脚本宝典收集整理的这篇文章主要介绍了JavaScript函数之call、apply以及bind方法案例详解,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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方法内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
@H_666_126@ 您可能感兴趣的文章:以上是脚本宝典为你收集整理的JavaScript函数之call、apply以及bind方法案例详解全部内容,希望文章能够帮你解决JavaScript函数之call、apply以及bind方法案例详解所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。