bind 的其中一個用法就是:綁定函數,使其不管怎麼樣調用都用相同的 this數組
示例:瀏覽器
var obj = { getThis: function() { console.log(this); } }; obj.getThis(); var getThisCopy = obj.getThis; getThisCopy();
運行結果以下:app
經過上述例子咱們會發現,雖然是 getThisCopy 是複製了 obj 的 getThis 方法,可是他們所屬的對象卻不同。在對象裏面,全部的 this 都指向對象自己,而在全局做用域定義的變量的 this 指向 Window。函數
示例:測試
var obj = { num: 100, numFun: function() { console.log(this.num); } }; var numFunCopy = obj.numFun; numFunCopy();
運行結果以下:this
緣由:複製了函數numFun,可是沒有複製num屬性,致使後面調用numFunCopy的時候,num是未定義的spa
bind 的存在就是 爲了解決 this 不可以指向原來的問題。code
因此,試試這段代碼:對象
var obj = { getThis: function(){ console.log(this); } } var getThisCopy = obj.getThis; obj.getThis(); getThisCopy.bind(obj)(); var obj = { num: 100, numFun: function(){ console.log(this.num); } } var numFunCopy = obj.numFun; obj.numFun(); numFunCopy.bind(obj)();
輸出結果以下:blog
總結:
總結bind使用方法:
fun.bind(thisArgument, argument1, argument2, ...)
thisArgument:在 fun 函數運行時指定的 this 值,若是綁定函數時使用 new 運算符構造的,則該值將被忽略。
argument1, argument2, ...:指定的參數列表。
返回值:具備指定 this 值和初始參數的給定函數的副本
使用1:建立綁定函數,使函數不管怎麼樣調用,都有相同的 this 值
this.x = 9; var module = { x: 81, getX: function() { return this.x; } }; module.getX(); // 返回 81 var retrieveX = module.getX; retrieveX(); // 返回 9, 在這種狀況下,"this"指向全局做用域 // 建立一個新函數,將"this"綁定到module對象 // 新手可能會被全局的x變量和module裏的屬性x所迷惑 var boundGetX = retrieveX.bind(module); boundGetX(); // 返回 81
語法:fun.call(thisArgument, argument1, argument2, ...)
thisArgument:在 fun 函數運行時指定的 this 值。在非嚴格模式下,該函數 this 指定爲 null 和 undefined ,則 this 值會自動只想全局對象,同時只爲原始值的 this 會指向該原始值的自動包裝對象。
argument*:指定的參數列表。
返回值:調用該方法的返回值,若是沒有,則返回undefined。
使用1:使用 call 方法來實現繼承
function Product(name,price){ console.info(this); this.name = name; this.price = price; } function Car(name,price){ Product.call(this,name,price); this.category = 'car'; } $(function(){ new Product(); var car = new Car('奔馳',100); console.info(car); });
測試結果:
使用2:使用 call 調用匿名函數,方法爲for循環傳入不一樣的對象
$(function(){ var people = [ {name:'aaa',age:10}, {name:'bbb',age:20}, ]; for(var i = 0;i<people.length;i++){ (function(i){ console.info('第'+i+'我的的名字:'+this.name+',年齡:'+this.age); }).call(people[i],i); } });
測試結果以下:
若是代碼修改成:
$(function(){ var people = [ {name:'aaa',age:10}, {name:'bbb',age:20}, ]; for(var i = 0;i<people.length;i++){ //(function(i){ console.info('第'+i+'我的的名字:'+this.name+',年齡:'+this.age); //}).call(people[i],i); } });
測試結果以下:
使用3:指定上下文 this
function greet(name,price){ var reply = [this.person,'aaa',this.role].join('|'); console.info(reply); } var i = { person:'bbb',role:'ccc' } $(function(){ greet.call(i); });
測試結果以下:
示例:
function add(a,b){ alert(a+b); } function sub(a,b){ alert(a-b); } add.call(sub,3,1);//彈出4,實際調用的是add()方法,只是add()方法中的this指向的是sub函數...
語法:fun.apply(thisArg [, argsArray])
thisArg:可選,在非嚴格模式下,若是 this 值設置爲 null/undefined,則 this 指向去全局對象(瀏覽器中就是 window 對象),同時爲原始值(數字,字符串,布爾值)的 this 會指向該原始的包裝對象。
argsArray:可選。數組或者類數組對象(從ES5開始可使用類數組對象)。
返回值:調用有指定this值和參數的函數的結果。
使用:其使用跟 call() 很是類似,只是提供參數的方式不一樣。