大家如果想了解改變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);
打印結果:
感謝大家的閱讀,如有不對的地方,可以向我提出,感謝大家!