call, apply, bind作用

call, apply作用就是(改变方法中的this指向)借用别人的方法来调用,就像调用自己的一样

 1 function Person(name) {
 2     this.name = name;
 3 }
 4 Person.prototype.getName=function () {
 5     return this.name;
 6 }
 7 function User ( name,password,age ) {
 8     this.name = name;
 9     this.password = password;
10     this.age = age;
11 }
12 
13 var user= new User('Bob',"123123",66);
14 alert(Person.prototype.getName.apply(user)); //"Bob"
user 通过alppy 借用Person原型中的方法getName

//call和apply用途一样,只是参数传递方式不一样

//call参数显式打散传递
//func.call(this, a, b, c, d);

//apply参数作为一个数组传递
//func.apply(this, arguments);
//func.apply(this, [a, b, c, d]);

 var fn2 = fn1.bind(this) 只改变this指向,不执行函数,返回值是一个函数;

1     var obj={
2         name:'bo'
3     };
4     function fn1() {
5         console.log(this.name);
6     }
7     var fn2 = fn1.bind(obj);
8     fn2();//bo

 

posted @ 2016-10-16 21:58  forever希望  阅读(222)  评论(0编辑  收藏  举报