常州武進區(qū)建設(shè)局網(wǎng)站吉林網(wǎng)站推廣公司
大家如果想了解改變this指向的方法,大家可以閱讀本人的這篇改變this指向的六種方法
大家有沒有想過這三種方法是如何改變this指向的?我們可以自己寫嗎?
答案是:可以自己寫的
讓我為大家介紹一下吧!
1.call()方法的原理
Function.prototype.calls = function (context, ...a) {// 如果沒有傳或傳的值為空對象 context指向windowif (typeof context == null || context == undefined) {context = window;}// 創(chuàng)造唯一的key值 作為我們構(gòu)造的context內(nèi)部方法名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);
打印結(jié)果:
2.apply()方法的原理
// apply與call原理一致 只是第二個參數(shù)是傳入的數(shù)組Function.prototype.myApply = function (context, args) {if (!context || context === null) {context = window;}// 創(chuàng)造唯一的key值 作為我們構(gòu)造的context內(nèi)部方法名let fn = Symbol();context[fn] = this;// 執(zhí)行函數(shù)并返回結(jié)果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]);
打印結(jié)果:
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// 處理參數(shù) 去除第一個參數(shù)this 其它傳入fn函數(shù)let arg = [...arguments].slice(1) //[...xxx]把類數(shù)組變成數(shù)組 slice返回一個新數(shù)組context[fn](arg) //執(zhí)行fndelete context[fn] //刪除方法}let obj = {func(a) {console.log(this);console.log(this.age);}}let obj1 = {age: "張三"}obj.func.myBind(obj1);
打印結(jié)果:
感謝大家的閱讀,如有不對的地方,可以向我提出,感謝大家!