if(!Function.prototype.bind){ Function.prototype.bind = function(obj){ var self = this; return function(){ return self.apply(obj); } }; }
使用方法:
var foo = { name:'foo'; sayName: function(){ console.log(this.name); } } foo.sayName.bind(foo);
2、prototype框架使用的this绑定方法可传递参数
if (!Function.bind) { Function.prototype.bind = function() { var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; };
使用方法:
func.bind(this, 1,2,3);//绑定并传递额外的参数1,2,3等