apply的模拟实现
文章目录
我们知道call和apply方法的作用基本一样,主要的区别在于第二个参数的传递,call直接传递参数即可,apply的需要传递一个参数列表。
因此call和apply的实现原理基本相同,可以参考https://segmentfault.com/a/11...
这样我们就直接上最终版的实现代码,如下
Function.prototype.apply2 = function (context, arr) {
context = context || window
var args = []
//遍历参数列表中的数据然后添加到args数组中
for (var i = 0; i < arr.length; i++) {
args.push('arr[' + i + ']')
}
// 在obj对象中添加fn属性,并且fn的值为函数bar
context.fn = this
// 执行fn方法,并返回值
const result = eval('context.fn(' + args + ')')
// 执行fn方法结束后,删除添加到obj中的fn方法
delete context.fn
return result
}
var obj = {
value: 1
}
function bar(name, age) {
console.log(name, age)
return {
value: this.value,
name,
age
}
}
console.log(bar.apply2(obj, ['张三', 18]))
使用ES6方法实现如下
Function.prototype.apply2 = function (context, arr) {
context = context || window
let fn = Symbol()
context.fn = this
const result = context.fn(...arr)
delete context.fn
return result
}
var obj = {
value: 1
}
function bar(name, age) {
console.log(name, age)
return {
value: this.value,
name,
age
}
}
console.log(bar.apply2(obj, ['张三', 18]))
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论