当前位置:网站首页>手动实现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
边栏推荐
猜你喜欢

JS中 t, _ => 的解析

Error in created hook: “ReferenceError: “Promise”未定义“

JS的解析与执行过程

CUDA project encountered a series of compilation problems after changing the environment (computer)

Shell脚本 &&和||的使用

cv_bridge 与opencv 版本不匹配的解决

FOC single resistance sampling position loop control servo motor

Collection of practical tips for C language (continuously updated)

Informatics one book pass - small ball

FOC SVPWM函数PWMC_SetPhaseVoltage解析
随机推荐
Mysql中的索引与视图
ES6新增方法
深蓝学院激光slam 理论与实践 第三章激光雷达去畸变 作业习题
js根据名字将数组对象中名字相同的项组成一个相同的数组
查漏补缺(三)
算数表达式
useCenterHook
深蓝学院激光slam理论与实践 -第二章(里程计标定)作业
el-form表单多重循环校验
往String原型上封装一个时间戳转日期的方法
MOS tube characteristics and conduction process
C语言结构体指定初始化
Analysis of fixed point PID code of FOC motor Library
查漏补缺(八)
ES6
js面试题:fn.call.call.call.call(fn2) 解析
PN结、二极管原理详解与应用
el-table添加序号
C语言代码规范
C language advanced notes 3