Function.prototype.newBind = function(context) { if (typeofthis !== "function") { thrownewTypeError( "Function.prototype.bind - what is trying to be bound is not callable" ); } var self = this; returnfunction() { return self.call(context); }; };
说明一下: if 判断是为了校验,只能让函数来调用此方法,并抛出错误。 第二个 return 是为了让返回的函数有返回值的功能。
测试一下:
1 2 3 4 5 6 7 8 9 10
var person = { name: "jayChou" };
var say = function() { console.log(this.name); };
var foo = say.newBind(person); foo(); // jayChou
成功啦。
二、传递参数
刚才的函数是没有传递参数,当然不行,所以我们想办法把函数的参数也传递进去。
bind 函数有个特点,就是在绑定的时候可以传参,返回的函数还可以继续传参。
1 2 3 4 5 6 7 8 9 10
var person = { name: "jayChou" };
var say = function(p1, p2) { console.log(this.name, p1, p2); };
var foo = say.bind(person, 18); foo(20); // jayChou 18 20
Function.prototype.newBind = function(context) { if (typeofthis !== "function") { thrownewTypeError( "Function.prototype.bind - what is trying to be bound is not callable" ); } var self = this; var args = Array.prototype.slice.call(arguments, 1); // 间接调用数组方法,获取第一次传的参数
Function.prototype.newBind = function(context) { if(typeofthis !== 'function') { thrownewTypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var self = this; var args = Array.prototype.slice.call(arguments, 1); // 间接调用数组方法,获取第一次传的参数