高版本的firefox,chrome及ie10以上的瀏覽器實現(xiàn)了Function.prototype.bind方法惕医,bind方法調(diào)用語法為:
functionObj.bind(thisArg[, arg1[, arg2[, ...]]])
使用范例參考如下:
function move(x, y) {
this.x += x;
this.y += y;
}
var point = {x:1, y:2};
var pointmove = move.bind(point, 2, 2);
pointmove(); // {x:3, y:4}
但是低版本瀏覽器中并未提供該方法,請給出兼容低版本瀏覽器的bind方法的代碼實現(xiàn)算色。
實現(xiàn)思路
- 回顧Function.prototype.bind用法:通過參數(shù)指定函數(shù)調(diào)用者和函數(shù)參數(shù)并返回該函數(shù)引用抬伺,可知
- 判斷瀏覽器是否兼容,不兼容就move添加一個bind的方法灾梦,讓其能夠調(diào)用move.bind
Function.prototype.bind
- 將參數(shù)轉(zhuǎn)換為數(shù)組保存
- 同時將數(shù)組返回
var _self = this, args = arguments;
return function() {
_self.apply(obj, Array.prototype.slice.call(args, 1));
}
* 所以可得
Function.prototype.bind= function(obj){
var _self = this, args = arguments;
return function() {
_self.apply(obj, Array.prototype.slice.call(args, 1));
}
}
* 在解題的過程中峡钓,有些知識點掌握不熟練導致花了很多時間理解妓笙,例如原型鏈,構(gòu)造函數(shù)能岩,構(gòu)造方法等等寞宫,搜尋網(wǎng)上的相關(guān)資料,有一個關(guān)于prototype的解析不錯:[Prototype源碼淺析——Function.prototype部分(一)](http://www.cnblogs.com/xesam/archive/2011/12/17/2290797.html)