Function.prototype.tkcall = function (thisArg, ...args) {//这里使用剩余参数,将参数保存在args数组内
// 步骤:1.获取需要被执行的函数
// 2.将thisArg转化为对象类型(防止传入非对象类型)
// 3.执行函数时将this绑定到thisArg
// 4.将函数执行结果返回
//1.获取被执行的函数
var fn = this;//这里是为了使用隐式绑定,将其绑定到thisArg上
//2.将thisArg转化为对象类型(防止传入非对象类型)
//普通数据非对象类型,使用Object将其转换为对应对象
//传入null或undefined时,将其绑定到window上
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : globalThis;
// 3.执行函数时将this绑定到thisArg
thisArg.fn = fn;
var result = thisArg.fn(...args);//这里使用拓展运算符,将args解构
delete thisArg.fn;
// 4.将最终的结果返回
return result;
}
function foo() {
console.log("foo函数被执行", this)
}
function sum(num1, num2) {
console.log("sum函数被执行", this, num1, num2);
return num1 + num2;
}
foo.tkcall(undefined);
var result = sum.tkcall("turnip", 20, 30);
console.log("tkcall的调用", result);
JavaScript之手写call函数
最新推荐文章于 2023-08-25 01:00:27 发布
这篇博客探讨了JavaScript中Function.prototype(tkcall)方法的实现,该方法用于改变函数调用时的上下文(this)并执行。通过tkcall,可以确保函数在指定的对象上下文中执行,同时提供了对参数的处理。示例中展示了foo函数和sum函数如何利用tkcall方法,展示了其在实际代码中的应用。

567

被折叠的 条评论
为什么被折叠?



