apply,call,bind

apply,call

apply and the call can change the point of this
      function f1(x,y) {
         console.log((x+y)+":===>"+this);
         return "这是函数的返回值";
       }
       //apply和call调用
       var r1=f1.apply(null,[1,2]);//此时f1中的this是window
       console.log(r1);
       var r2=f1.call(null,1,2);//此时f1中的this是window
       console.log(r2);
       console.log("=============>");
       //改变this的指向
       var obj={
         sex:"男"
       };
       //本来f1函数是window对象的,但是传入obj之后,f1函数此时就是obj对象的
       var r3=f1.apply(obj,[1,2]);//此时f1中的this是obj
       console.log(r3);
       var r4=f1.call(obj,1,2);//此时f1中的this是obj
       console.log(r4);
apply and call to use
apply的使用语法
     函数名字.apply(对象,[参数1,参数2,...]);
     方法名字.apply(对象,[参数1,参数2,...]);
call的使用语法
     函数名字.call(对象,参数1,参数2,...);
     方法名字.call(对象,参数1,参数2,...);

作用:改变this的指向
    不同的地方:参数传递的方式是不一样的
    只要是想使用别的对象的方法,并且希望这个方法是当前对象的,那么就可以使用apply或者是call的方法改变this的指向

bind

bind方法是复制的意思,参数可以在复制的时候传进去,也可以在复制之后调用的时候传入进去
apply和call是调用的时候改变this指向
bind方法,是赋值一份的时候,改变了this的指向


function Person(age) {
      this.age=age;
    }
    Person.prototype.play=function () {
      console.log(this+"====>"+this.age);
    };

    function Student(age) {
      this.age=age;
    }
    var per=new Person(10);
    var stu=new Student(20);
    //复制了一份
    var ff=per.play.bind(stu);
    ff();
    //bind是用来复制一份
    //使用的语法:
    /*
    * 函数名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个函数
    * 方法名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个方法
    *
    * */

A more detailed than I https://www.cnblogs.com/moqiutao/p/7371988.html

Guess you like

Origin www.cnblogs.com/huihuihero/p/11334595.html