JS中改变指向的三种方法

174 阅读1分钟

在JS中改变this指向的方法有:

1.call

 <script>
        // 1.call()
        let o = {
            name: 'andy'
        }

        function fn(a, b) {
            console.log(this);
            console.log(a + b);
        };
        fn.call(o, 1, 2);
        // call第一个可以调用函数 第二还可以改变函数内的this指向
        // call的主要作用可以实现继承

        function Father(uname, age, sex) {
            this.uname = uname;
            this.age = age;
            this.sex = sex;
        }

        function Son(uname, age, sex) {
            Father.call(this, uname, age, sex);
        }
        let son = new Son('刘德华', 18, '男');
        console.log(son);
</script>

image.png

2.apply

 // 2.apply() 应用运用的意思
        let o = {
            name: 'andy'
        };

        function fn(arr) {
            console.log(this);
            console.log(arr); // 'pink'
        };
        fn.apply(o, ['pink']);
        // 1.第一个也是调用函数 第二个可以改变函数内部的this指向
        // 2.但是他的参数必须是数组(伪数组)
        // 3.appy的主要应用比如说我们可以利用 apply 借助于数学内置对象求最大值
        // Math.max();
        let arr = [1, 66, 3, 99, 4];
        //let max Math.max.apply(null,arr);
        let max = Math.max.apply(Math, arr);
        let min = Math.min.apply(Math, arr);
        console.log(max, min);

image.png

3.bind

<script>
        // 3.bind() 绑定捆绑的意思
        let o = {
            name: 'andy'
        }

        function fn(a, b) {
            console.log(this);
            console.log(a + b);
        };
        let f = fn.bind(o, 1, 2);
        f();
        // 1.不会调用原来的函数 可以改变原来函数内部的this指向
        // 2. 返回的是原函数改变this之后产生的新函数
        // 3.如果有的函数我们不需要立即调用,但是又想改变这个函数内部的this指向此时用bind
        // 4.我们有一个按钮,当我们点击了之后,就禁用这个按钮,3秒钟之后开启这个按钮
        // let btn1 = document.querySelector('button');
        // btn1.onclick = function() {
        //     this.disabled = true; // 这个this指向的是btn这个按钮
        //     // let that = this;
        //     setTimeout(function() {
        //         // that.disabled = false; //定时器函数里面的this指向的是window
        //         // this.disabled = false; //此时定时器函数里面的this指向的是btn

        //     }.bind(this), 3000); // 这个this指向的是btn这个对象
        // }
        // let btns = document.querySelectorAll('button');
        // for (let i = 0; i < btns.length; i++) {
        //     btns[i].onclick = function() {
        //         this.disabled = true;
        //         setTimeout(function() {
        //             this.disabled = false;
        //         }.bind(this), 2000);
        //     }
        // }
    </script>

image.png

总结:

相同点:

都可以改变函数内部的this指向

区别点:

1.call和apply会调用函数并且改变函数内部this指向
2.call和apply传递的参数不一样,call传递参数aru1,aru2...形式apply必须数组形式[arg]
3.bind不会调用函数可以改变函数内部this指向

主要应用场景:

1.call经常做继承
2.appy经常跟数组有关系。比如借助于数学对象实现数组最大值最小值
3.bind不调用函数,但是还想改变this指向,比如改变定时器内部的this指向