原生Js的bind

@菜鸡@杂鱼@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,并且将参数拼接
       }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值