改变this指向的三种方法,call,apply和bind的区别与联系

this指向(永远指向最后调用它的对象)

  • 一般直接调用函数时,this指向window。
  • 当事件调用函数时,this指向触发该事件的对象。
  • 而当调用对象的方法时,在函数中this指向拥有该方法的对象。
    但是

call( ),apply( ) 和 bind( ) 都是Function的方法,所有函数都有这三个方法。

1. 相同点

都用来改变this的指向

2.不同点

接收参数的方式不同

(1)call

形式:call (this要指向对象,传参逐个列举(可能多个))

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
    function fn1(a,b){
        console.log(a+b);
    }
    function fn2(a,b){
        //下面的this指向调用call方法的fn1,即this指向fn1,且把age为1传给fn1中
       fn1.call(this,10,20); // 30
    }
    fn2(1,2);
    </script>
</body>
</html>
(2)apply

形式:apply(this要指向对象,arguments) 或 fn.apply(this要指向对象, 传参的数组)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
    function fn1(a,b){
        console.log(a+b);
    }
    function fn2(a,b){
        // arguments把a,b的1,2传给fn1。
       fn1.apply(this,arguments); // 3
       fn1.apply(this,[20,30]); // 50
    }
    fn2(1,2);
    </script>
</body>
</html>
(3)bind

形式:bind(this要指向对象) 不会立即执行,并且返回一个改变this指向的函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
    window.color = "red";
    var obj = {
        color: "blue"
    }
    function fn1(){
        console.log(this.color);
    }
    var a = fn1.bind(obj);
    //此时this指向obj.  this.color则为obj的属性blue
    a(); //blue
    </script>
</body>
</html>

所以,bind后函数不会执行,而只是返回一个改变了上下文的另一个函数,而call和apply是直接执行函数。若无参数,apply与call基本没什么区别

注意:在一般函数中,this在调用的时候才确定,但是在箭头函数中,一旦箭头函数定义,它的this就已经确定,且无法改变。箭头函数中的this指向离自己最近的非箭头函数作用域里。

发布了24 篇原创文章 · 获赞 26 · 访问量 2723

猜你喜欢

转载自blog.csdn.net/apple_2021/article/details/101227330