欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js——apply,call和bind方法

程序员文章站 2024-02-28 20:00:10
...
  1. apply和call方法

    /**
     * apply和call的使用方法
     *
     * apply的使用语法:
     * 函数名字.apply(对象,[参数1,参数2,......]);
     * 方法名字.apply(对象,[参数1,参数2,......]);
     *
     * call的使用语法:
     * 函数名字.call(对象,[参数1,参数2,......]);
     * 方法名字.call(对象,[参数1,参数2,......]);
     *
     * 作用:改变this的指向
     * 不同的地方:参数传递的方式是不一样的
     *
     * 只要想使用别的对象的方法,并且希望这个方法是当前对象食物,那么就可以使用apply或者call的方法改变this指向
     */
     //例子
    function Person(age,sex){
        this.age=age;
        this.sex=sex;
    }
    Person.prototype.play= function () {
        console.log(this.sex);
        return 12113333333334;
    };
    var per=new Person(12,"男");
    per.play();
    console.log("******************************");
    function Student(name,sex){
        this.name=name;
        this.sex=sex;
    }
    var stu=new Student("小明","女");
    var r1=per.play.apply(stu,[10,20]);
    var r2=per.play.call(stu,10,20);
    console.log(r1);
    console.log(r2);
    
  2. bind 方法

  //bind是用来复制一份
       /**
        * 使用的语法:
        *
        * 函数名字.bind(对象,参数1,参数2,.....);------返回值是复制之后的这个函数
        * 方法名字.bind(对象,参数1,参数2,.....);------返回值是复制之后的这个方法
        */
        function Person(name,age){
           this.name=name;
           this.age=age;
       }
        Person.prototype.play= function () {
            console.log(this+"+++++++"+this.age);
        };
        function Student(age){
            this.age=age;
        }
        var per=new Person("小明",30);
        var stu=new Student(40);
        var ff=per.play.bind(stu);
        ff();

        //apply和call是调用的时候改变this指向
        //bind方法,是复制一份的时候改变this指向
        function f1(x,y){
            console.log((x+y)+"+++++++++"+this);
        }
        //var f=f1.bind(null,10,20);
        var f=f1.bind(null);
        f(10,20);