js中关于call()、apply()、bind()的用法

148 阅读2分钟

bind、call、apply

每个函数都包含一个prototype属性,这个属性是指向一个对象的引用,这个对象称之为原型对象。当将函数用作构造函数的时候,新创建的对象会从原型对象上继承属性。

apply方法

apply方法实现继承(例):
   /*定义一个人类*/
        function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        /*定义一个学生类*/
        function Student(name, age, grade) {
            Person.apply(this, arguments); //Person.call(this,name,age);
            this.grade = grade;
        }
        //创建一个学生类  
        var student = new Student("zhangsan", 21, "一年级");
        console.log("name:" + student.name + "\n" + "age:" + student.age + "\n" + "grade:" + student.grade)
        
   打印结果:
           name:zhangsan
           age:21
           grade:一年级
        
        //apply方法构造一个参数数组传递给函数,同时自己设置this的值,
        apply函数接收两个参数,第一个是传递给这个函数用来绑定this的值,
        第二个是一个参数数组
        
        作用:调用函数、指定函数运行时的指向

call方法

   call方法实现继承(例):
           function Father(uname) {
            this.uname = uname;
        }

        function Son(uname, age) {
            //通过call方法实现继承
            Father.call(this, uname);
            this.age = age;
        }
        var s1 = new Son('张三', 18);

        console.log(s1.hasOwnProperty('uname')); 
        console.log(s1);
        
        打印结果:
        true
        Object{uname:"张三",age:18}

        //call方法同样将第一个参数绑定给this的值,但后面接受的是不定参数,不再是一个数组
        
        作用:调用函数、指定函数运行时的指向

bind方法

bind应用(例):
如果我们想改变某个函数内部的this指向,但又不需要立即调用该函数,此时用bind。
<body>
//我们有一个按钮,当我们点击了之后,就禁用这个按钮,3秒中之后再自动开启这个按钮

    <button>点击按钮</button>
    <script>
        var btn = document.querySelector('button');
        btn.onclick = function() {
            this.disabled = true //禁用按钮。
            setTimeout(function() {
                    console.log(this) //此时this指向的是btn这个按钮对象
                    this.disabled = false;
                }.bind(this), 3000) //这个this是在定时器函数外,所以指向的是btn这个按钮对象。此处也可以写成.bind(btn)
        }
    </script>
</body>

//bind方法与call、apply不同之处在于,bind方法不会调用函数,返回值是一个原函数的拷贝

作用:指定函数运行时this的指向、返回由指定的this值和初始化参数构造的原函数得拷贝