JS中call()、apply()、bind()改变this指向的原理

大家有没有想过这三种方法是如何改变this指向的?我们可以自己写吗?

答案是:可以自己写的

让我为大家介绍一下吧!

1.call()方法的原理

javascript 复制代码
	Function.prototype.calls = function (context, ...a) {
		// 如果没有传或传的值为空对象 context指向window
		if (typeof context == null || context == undefined) {
			context = window;
		}
		// 创造唯一的key值  作为我们构造的context内部方法名
		let fn = Symbol();
		// this指向context[fn]方法
		context[fn] = this;
		return context[fn](...a);
	}
	let obj = {
		func(a,b){
			console.log(this);
			console.log(this.age);
			console.log(a);
			console.log(b);
		}
	}
	let obj1 = {
		age:"张三"
	}
	obj.func.calls(obj1,1,2);

打印结果:

2.apply()方法的原理

javascript 复制代码
	// apply与call原理一致  只是第二个参数是传入的数组
	Function.prototype.myApply = function (context, args) {
		if (!context || context === null) {
			context = window;
		}
		// 创造唯一的key值  作为我们构造的context内部方法名
		let fn = Symbol();
		context[fn] = this;
		// 执行函数并返回结果
		return context[fn](...args);
	};
	let obj = {
		func(a, b) {
			console.log(this);
			console.log(this.age);
			console.log(a);
			console.log(b);
		}
	}
	let obj1 = {
		age: "张三"
	}
	obj.func.myApply(obj1, [1,2]);

打印结果:

3.bind()方法的原理

javascript 复制代码
	Function.prototype.myBind = function (context) {
		// 如果没有传或传的值为空对象 context指向window
		if (typeof context === "undefined" || context === null) {
			context = window
		}
		let fn = Symbol(context)
		context[fn] = this //给context添加一个方法 指向this
		// 处理参数 去除第一个参数this 其它传入fn函数
		let arg = [...arguments].slice(1) //[...xxx]把类数组变成数组 slice返回一个新数组
		context[fn](arg) //执行fn
		delete context[fn] //删除方法
	}
	let obj = {
		func(a) {
			console.log(this);
			console.log(this.age);
		}
	}
	let obj1 = {
		age: "张三"
	}
	obj.func.myBind(obj1);

打印结果:

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

相关推荐
一次旅行6 小时前
【AI工具】Rust-Based CLI:用 xargs 和并行加速你的 Linux 日常
linux·开发语言·rust
老毛肚6 小时前
juc线程通信
java·开发语言·jvm
跨境数据猎手7 小时前
反向海淘实战|独立站搭建+国内电商API对接
开发语言·爬虫·架构
没钥匙的锁17 小时前
05-Java面向对象构造器与封装
java·开发语言
仙人球部落7 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2401_894915537 小时前
Geo搜索优化排名源码部署搭建全流程详解
android·开发语言·flask·php·精选
chouchuang8 小时前
day-025-面向对象-上
开发语言·python
sunfdf8 小时前
Next.js 新手从零部署到首跑实战指南
开发语言·javascript·ecmascript
SmartBoyW8 小时前
前端死磕:一文彻底搞懂 JS 事件循环 (Event Loop) 与宏微任务
前端·javascript
hold?fish:palm9 小时前
从源码到可执行文件:C++程序的编译过程
开发语言·c++