当前位置:网站首页>手动实现call,apply,bind函数
手动实现call,apply,bind函数
2022-04-23 05:54:00 【MiMenge】
实现call
Function.prototype.myCall = function (targetObj, ...resule) {
// 判断传入对象的有无
targetObj = targetObj || window;
// 向传入对象上挂在this指向,此时this指向调用myCall函数
targetObj.fn = this;
// 在内部使用传入对象调用fn方法,这样可以实现更改this指向,指向为传入的目标对象
let value = eval('targetObj.fn(...resule)');
// 删除目标对象的fn方法
delete targetObj.fn
// 返回调用的结果
return value;
}
let obj = {
uname: 'Tom'
}
function demo(a, b){
console.log(this.uname, a, b);
}
demo();// undefined undefined undefined
demo.myCall(obj, 1, 2);
// Tom 1 2
实现apply (主体和call差不多, 不同的传入参数的方式)
Function.prototype.myApply = function (targetObj, resule) {
targetObj = targetObj || window;
targetObj.fn = this;
let value = eval('targetObj.fn(...resule)');
delete targetObj.fn
return value;
}
let obj = {
uname: 'Tom'
}
function demo(x, y){
console.log(this.uname, x, y);
}
demo();// undefined undefined undefined
demo.myApply(obj, [1, 2]);
// Tom 1 2
实现bind
Function.prototype.myBind = function (targetObj, ...resule) {
// 判断调用的对象是否是一个函数
if (typeof this !== "function") {
throw new Error("this must be a function");
}
// 创建变量保存this指向
// 此时this指向外部调用的函数
let self = this;
// 创建要返回的函数
let backFunc = function () {
// 先判断调用对象的this是否和本函数时同一个this
// 是则更改this指向到自身,(实际上最后返回的也只是this指向自身的函数)
// 不是则改变调用者this指向指向传入对象,将参数传递到调用的this中。
self.apply(this instanceof self ?
this : targetObj, resule.concat(Array.prototype.slice.call(arguments)));
}
// 判断调用是有原型
if(this.prototype) {
// 有则赋值原型到返回的函数上
backFunc.prototype = Object.create(this.prototype);
}
// 返回函数
return backFunc;
}
let obj = {
uname: 'Tom'
}
function demo(x, y){
console.log(this.uname, x, y);
}
demo();// undefined undefined undefined
demo.myBind(obj, 1, 2)();
// Tom 1 2
版权声明
本文为[MiMenge]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_53584564/article/details/123493696
边栏推荐
- Error in created hook: “ReferenceError: “Promise”未定义“
- POJ-The Unique MST
- 【无标题】js中的类型判断
- CUDA project encountered a series of compilation problems after changing the environment (computer)
- C语言结构体指定初始化
- 金额输入框,用于充值提现
- 特效案例收集:鼠标星球小尾巴
- token详解以及应用原理
- excel里有文字的数字怎么从小到大排序,而不是首数字排序
- [stepping on the pit] MELD in win11 wsl2 cannot be used normally. Problem repair
猜你喜欢
随机推荐
excel里有文字的数字怎么从小到大排序,而不是首数字排序
realsense 选型大对比D455 D435i D415 T265 3D硬件对比
Set up a personal blog of jpress
Multibyte and Unicode in VS
Detailed explanation and application principle of token
Node的文件系统及Buffer概述
Collection of practical tips for C language (continuously updated)
赛氪-zeal
Krypton zeal
查漏补缺(八)
Assembler 32-bit unsigned addition calculator
Informatics one book pass - small ball
Shell脚本的通配符和特殊符号
HDU-Memory Control
v-for下定时给图片添加动画
undefined reference to `Nabo::NearestNeighbourSearch
五个路由守卫的使用
Arm common assembly instructions
谈谈v-if显示隐藏问题
Vs can be compiled, but there will be a red underline to indicate the problem of undefined identifiers









