1. 程式人生 > >apply和call和bind方法

apply和call和bind方法

apply和call都可以讓函式或方法呼叫,傳入引數和自己呼叫的寫法不一樣,但是效果是一樣的

   function f1(x,y) {
     console.log("結果是:"+(x+y)+this);
     return "10000";
   }
   f1(10,20);//函式的呼叫
 f1.apply(null,[100,200]);
 f1.call(null,100,200);


//apply和call可以改變this的指向


    function Person(age,sex) {
      this.age=age;
      this.sex=sex;
    }
    //通過原型新增方法
    Person.prototype.sayHi=function (x,y) {
      console.log("您好啊:"+this.sex);
      return 1000;
    };
    var per=new Person(10,"男");
    per.sayHi();

    console.log("==============");
    function Student(name,sex) {
      this.name=name;
      this.sex=sex;
    }
    var stu=new Student("小明","人妖");
    var r1=per.sayHi.apply(stu,[10,20]);
    var r2=per.sayHi.call(stu,10,20);

    console.log(r1);
    console.log(r2);

//apply和call的使用方法          * apply的使用語法     * 函式名字.apply(物件,[引數1,引數2,...]);     * 方法名字.apply(物件,[引數1,引數2,...]);     * call的使用語法     * 函式名字.call(物件,引數1,引數2,...);     * 方法名字.call(物件,引數1,引數2,...);     *     * 作用:改變this的指向     * 不同的地方:引數傳遞的方式是不一樣的     *     * 只要是想使用別的物件的方法,並且希望這個方法是當前物件的,那麼就可以使用apply或者是call的方法改變this的指向     *     * 


    //方法改變this的指向

//    function Person(age) {
//      this.age = age;
//    }
//    Person.prototype.sayHi = function (x, y) {
//      console.log((x + y) + ":====>" + this.age);//是例項物件
//    };
//
//    function Student(age) {
//      this.age = age;
//    }
//    var per = new Person(10);//例項物件
//    var stu = new Student(100);//例項物件
//    //sayHi方法是per例項物件的
//    per.sayHi.apply(stu, [10, 20]);
//    per.sayHi.call(stu, 10, 20);

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,...);---->返回值是複製之後的這個方法     *     * */