← 返回首页
Javascript基础教程(四十二)
发表时间:2021-04-27 20:52:03
深入探讨Javascript的this指向

1.当调用成员方法时,this默认指向调用当前方法的那个对象。

当调用成员方法时,this默认指向调用当前方法的那个对象。可以通过call()来改变调用当前方法的对象。

let p1 = {
        name: '张三',
        age : 18,
        introduce:function(){
            console.log("name is:"+this.name+",age is:"+this.age); 
        }
    }

let p2={
     name: '李四',
     age: 20
}

p1.introduce();  //p1.introduce.call(p1);
p1.introduce.call(p2);

运行结果:
name is:张三 ,age is:18
name is:李四 ,age is:20

2.如果有new关键字,this总是指向new出来的那个新对象

    let temp;
    function Person(name,age){
        this.name = name;
        this.age = age;
        temp = this;
    }

    let p1 = new Person('张三',18);
    console.log(p1===temp);
    let p2 = new Person('李四',20);
    console.log(p1===temp);
    console.log(p2===temp);

运行结果:
true
false
true

3.DOM事件中,如果使用addEventListener方式注册事件监听器,this指向事件源对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <button id="bt1" onclick="handleClick()">点我1</button><br>
    <button id="bt2">点我2</button><br>
</div>
<script>
    //通过onclick属性绑定的事件,this指向window 
    function handleClick(){
        console.log(this);
    }
    //给按钮动态注册事件监听器
    document.getElementById("bt2").addEventListener("click",function(){
        console.log(this);
    })
</script>
</body>
</html>

运行结果:
window
<button id="bt2">点我2</button>

4.在回调函数中,this默认指向window

    var age = 100;
    function foo(){
        console.log(this.age);
    }

    let p1 = {
        name: '张三',
        age : 18,

        fn: function(callback){
           callback();
        }
    }
    p1.fn(foo);

运行结果:
100

如果想改变回调函数的this指向可以通过call();例如:

    var age = 100;
    function foo(){
        console.log(this.age);
    }

    let p1 = {
        name: '张三',
        age : 18,

        fn: function(callback){
           callback.call(this);
        }
    }
    p1.fn(foo);

运行结果:
18

5.箭头函数this在函数定义时绑定且不可改变属于静态绑定。

箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象,并且this指向不能改变。

++箭头函数里的this总是指向上一层作用域。++ ,并且对象不构成新的作用域。

下面的例子你可以认为是指向window对象。

    var age = 100;

    let p1 = {
        name: '张三',
        age : 18,
        introduce:()=>console.log("name is:"+this.name+",age is:"+this.age)
    }

    p1.introduce();

运行结果:
100

如果不使用箭头函数,this指向调用当前方法的对象。

    var age = 100;

    let p1 = {
        name: '张三',
        age : 18,
        introduce:function(){
            console.log("name is:"+this.name+",age is:"+this.age)
        }
    }

    p1.introduce();

运行结果:
name is:张三,age is:18

小结:

  1. 当调用对象的成员方法时,this通常指向调用当前方法的哪个对象。
  2. 在构造函数中的this,通常指向刚new出来的新对象。
  3. 在Dom动态绑定事件监听器的事件处理函数中的this通常绑定到事件源对象(箭头函数除外)
  4. 回调函数中this通常绑定到window对象。
  5. 箭头函数是静态绑定,永远绑定到上一层作用域,并且对象不构成新的作用域。

推荐:当你在实际编程中不清楚此时此刻this究竟指向哪个对象,强烈推荐使用console.log(this);输出一下结果,咱们心里就明白了。