this的指向在javascript中一直是個謎同樣的存在,可是不少地方又會用到this,因此理解和使用this很是重要,關於this的理解這篇文章不作介紹,由於這篇的目的是改變this的指向。javascript
改變this的指向有三種方法,call,apply,bind。下面先介紹下這三種方法java
var a = { name:"aaa", say(type){ console.log(type,this.name); } } a.say("at");//at aaa var tn = {name:"ttt"}; a.say.call(tn,"tt")//tt ttt
能夠看到經過call,say方法中的this指向了tn,傳參的方式的列舉面試
var a = { name:"aaa", say(type){ console.log(type,this.name); } } a.say("at"); var tn = {name:"ttt"}; a.say.apply(tn,["tt"])
能夠看到經過apply,say方法中的this指向了tn,傳參的方式是數組數組
bind也能改變this的指向,不過和call,apply不一樣的地方在於,bind只改變this,不會指向函數app
var a = { name:"aaa", say(type){ console.log(type,this.name); } } var tn = {name:"ttt"}; var b = a.say.bind(tn); b();//ttt
bind 改變this,也是可以繼承原型鏈的,看下下面的代碼函數
var to = {name:"to",color:"red"}; function Animal(){ console.log(`name:${this.name}...color:${this.color}`); } Animal.prototype.say = function(){ console.log(`say..name:${this.name}...color:${this.color}`); } var Cat = Animal.bind(to); Cat();//name:to...color:red var cat = new Cat();// name:undefined...color:undefined cat.say();//say..name:undefined...color:undefined
由於cat是Cat的實例,Cat是改變了this的Animal,因此cat也是Animal的實例,可是this是指向cat的,因此this.name是undefinedthis
Function.prototype.bind = function(obj){ const args = Array.prototype.slice.call(arguments,1);//保留bind時的參數 const that = this; const bound = function(){ const inArgs = Array.prototype.slice.call(arguments);//執行bind的函數時的參數 const newArgs = args.concat(inArgs);//組裝參數 that.apply(obj,newArgs);//執行bind的函數 } //繼承prototype--寄生組合式繼承 function F(){}; F.prototype = that.prototype; bound.prototype = new F(); return bound; }
而後執行上面的代碼es5
Cat();//name:to...color:red var cat = new Cat();//name:to...color:red cat.say();//say..name:undefined...color:undefined
不過第二行和原生的bind仍是有點區別的,這裏仍是記住了以前的bind的對象,原生的不知道爲啥是undefinedprototype
實現es5中的bind方法,使得下面的代碼輸出successcode
function Animal(name,color){ this.name = name; this.color = color; } Animal.prototype.say = function(){ return `i am a ${this.color} ${this.name}` } const Cat = Animal.bind(null,"cat"); const cat = new Cat("white"); if(cat.say() === 'i am a white cat' && cat instanceof Cat && cat instanceof Animal){ console.log("success") }
加上上面的bind實現,咦??沒有出現success??爲何?
分析一下代碼,bind的第一個參數是null??null的時候應該默認爲this,修改代碼以下
Function.prototype.bind = function(obj){ const args = Array.prototype.slice.call(arguments,1);//保留bind時的參數 const that = this; const bound = function(){ const inArgs = Array.prototype.slice.call(arguments);//執行bind的函數時的參數 const newArgs = args.concat(inArgs);//組裝參數 const bo = obj || this; that.apply(bo,newArgs);//執行bind的函數 } //繼承prototype--寄生組合式繼承 function F(){}; F.prototype = that.prototype; bound.prototype = new F(); return bound; }
輸出success完美~~~撒花~~~