@菜鸡@杂鱼@Kevin
前段时间看了些有关原生js中bind的文章,在做了一些试验之后,表示要总结一番
bind是ECMAScript5.1新增的内容,但IE6,7,8不支持bind方法,为了解决这个问题,此处需要给Function。prototype添加一个bind方法,其定义为:
Function.prototype.bind(thisArg [, arg1 [, arg2, …]])
将调用bind方法的对象中的this绑定到thisArg中,并传入参数,如:
var AFunction = function(myArg) {
this.myArg= myArg;
console.log(this. myArg);
}
var BFunction = function() {
this.myArg = "B's Arg";
this.myString = "B's String";
console.log(this.myArg);
console.log(this.myString);
}
var A = new AFunction("A's Arg");
BFunction.bind(A);
var B = new BFunction();
B();
以上代码执行完之后得到的是
A's Arg
B's String
用字面量的方式,在Candy示例中,将字面量obj 绑定在方法A中,A中this也就是字面量,那么this.age也就是字面量Candy中的age,在Sweety示例中,将age以参数的形式传入:
var Candy = {
gender: female,
age: 24
}
var Sweety = {
gender: female,
}
<pre name="code" class="javascript">function A (age) {
this.age = age;
console.log("this is a " + this.gender + "who is " + this.age + "years old.")
}
function B (age) { this.age = age; console.log("this is a " + this.gender + "who is " + this.age + "years old.")}A.bind(Candy);
var a = new A;
a(); // this is a female who is 24 years old.B.bind(Sweety,25);
var b = new B;
b(25); // this is a female who is 25 years old.
另外一种用法是:
var Candy = $('#Candy'),
Sweety = $('#Sweety');
Candy.click(function(){
console.log(this.id);
}.bind(Sweety));//此处执行结果"Sweety".
来看bind函数的源码:
Function.prototype.bind = Function.prototype.bind || function(obj) {//如果bind方法已存在,则无需添加
var _this = this;
var args = Array.prototype.slice.call(arguments, 0); // 因为arguments 是一个object, 它没有slice方法,直接用argument.slice()会报错。
return function(_this) {
return _this.apply(obj, args.concat( Array.prototype.slice.call(arguments)));//替换this,并且将参数拼接
}
}