书本翻页 网站模板,广州公司网站建设推广,手机网站建设事项,门户网站还能建设么大家如果想了解改变this指向的方法#xff0c;大家可以阅读本人的这篇改变this指向的六种方法 大家有没有想过这三种方法是如何改变this指向的#xff1f;我们可以自己写吗#xff1f; 答案是#xff1a;可以自己写的 让我为大家介绍一下吧#xff01;
1.call()方法的原理…大家如果想了解改变this指向的方法大家可以阅读本人的这篇改变this指向的六种方法 大家有没有想过这三种方法是如何改变this指向的我们可以自己写吗 答案是可以自己写的 让我为大家介绍一下吧
1.call()方法的原理 Function.prototype.calls function (context, ...a) {// 如果没有传或传的值为空对象 context指向windowif (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()方法的原理 // 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()方法的原理 Function.prototype.myBind function (context) {// 如果没有传或传的值为空对象 context指向windowif (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) //执行fndelete context[fn] //删除方法}let obj {func(a) {console.log(this);console.log(this.age);}}let obj1 {age: 张三}obj.func.myBind(obj1);打印结果 感谢大家的阅读如有不对的地方可以向我提出感谢大家