this软绑定

当this不存在,或为undefined || window时,那么就用传入的Obj为this,否则就用当前的this。

if(!Function.prototype.softBind){
Function.prototype.softBind = function(obj){
var fn = this;
var curried = [].slice.call(arguments,1);
var bound = function(){
return fn.apply(
(!this || this === (window || global)) ? obj : this, curried.concat.apply(curried,arguments)
)
};
bound.prototype = Object.create(fn.prototype);
return bound;
}
}

function foo(){
console.log('name:' + this.name);
}

var obj = {name : 'obj'},
obj2 = {name : 'obj2'},
obj3 = {name : 'obj3'};

var fooOBJ = foo.softBind(obj);

fooOBJ();

posted @ 2015-05-28 15:55  何君  阅读(227)  评论(0编辑  收藏  举报