語法:app
fn.bind(obj,arg1,arg2,arg3...)函數
bind是es5新增的方法,顧名思義,它的做用是將函數綁定到某個對象上,就像是某個對象調用方法同樣。其本質仍是改變了該函數的上下文(context),它跟call和apply不同的地方是,在調用以後會生成一個新函數。好比:this
var x = y = 2, function fn(){ return this.x + y; } var obj = {x:1}; var obj1 = fn.bind(obj); obj1();//3
而es3中卻沒有此方法,我會這樣去實現:es5
function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; }
若是想要是每一個函數都使用bind的方法能夠這樣:spa
if(!Function.prototype.bind){ Function.prototype.bind = function(obj) { var that = this; return function () { return that.apply(obj, arguments); }; } }