JavaScript中的this指向

116 阅读1分钟

学习JavaScript我们都会遇到this指向的问题,下面我们就来看一下this在JavaScript中的表现吧。

  1. 在JavaScript的对象中。

    var obj = {
       name:"jack",
       getName(){
           console.log(this)
       }
     }
     obj.getName(); // this指向对象的本身
    
  2. 在普通的函数中。

     function getNumber(){
        console.log(this); //this指向了window
    }
    getNumber();
    
  3. 在箭头函数中。

    (()=>{
        console.log(this); //同样指向了window
    })()
    
  4. 在严格模式中

     "use strict"
     function getNumber() {
        console.log(this); //this是undefined
     }
    getNumber();
    
  5. 在构造函数中

    function Person (name,age){
        this.name = name;
        this.age = age;
        console.log(this); //this指向了当前实例化的对象
    }
    var student = new Person("张三",16)
    var student = new Person("李四",16)
    

结论:谁调用这个函数,this就指向他。要记住在严格模式下输出的是undefined而不是window。