前端总结面试题(每日更新)第六天

今天因为时间有些紧,咱们来讨论一下this指向问题吧,相信这个问题也困扰了很多同窗,面试的时候,通常都会有这样的基础问题,但愿你们多多点赞,来鼓励一下小弟,小弟这厢有礼了哈哈。。。面试

结合ES5和ES6咱们来看看this的问题吧

this 是一个关键字,它表明函数运行时,自动生成的一个内部对象,只能在函数内部使用。bash

  • 做为纯粹的函数调用, this指向全局对象;app

    function fn () {
      console.log(this);
    }
    fn()  // Window
    
    var fn = function() {
      console.log(this);
    };
    fn();  //  Window
    
    (function(){
      console.log(this);
    })();  //Window
    
    function fn1(){
      function fn2() {
        console.log(this)
      }
      fn2();
    }
    fn1();  //Window
    复制代码
  • 做为构造函数被调用, this指向新的对象(new 会改变this的指向);函数

    // 【在构造函数中this指向当前建立的对象】
        function Student(name,age) {
          this.name = name;
          this.age =age;
        }
    
        Student.prototype.sayHi = function() {
          console.log('我叫' + this.name);
        };
    
        var stu1 = new Student('张三',10);
        var stu2 = new Student('李四',10);
    复制代码
  • 做为对象的方法调用, this指向调用对象;ui

    //借用上面的例子
       stu1.sayHi();
       stu2.sayHi();
    复制代码
  • 箭头函数的this指向是外部的第一个纯粹函数(其实箭头函数是没有this指向的)。this

    function a() {
        return () => {
            return () => {
            	console.log(this)
            }
        }
    }
    console.log(a()()())   //Window
    复制代码
  • 定时器中的this指向Windowspa

    setTimeout(function(){
      console.log(this)
    },1000);  //Window
    复制代码
  • 事件处理程序中this的指向事件源prototype

    // 【在事件处理程序中,this指向事件源】
        document.onclick = function() {
          console.log(this);
        };
    复制代码

    改变this的指向

    call方法

    • 语法:函数名.call(调用者,参数1...)code

    • 做用:函数被借用时,会当即执行,而且函数体内的this会指向借用者或调用者对象

    • 代码

      function fn(name, age) {
         this.name = name;
         this.age = age;
       }
      
       // 对象字面量
       var obj = {};
       fn.call(obj, '李四', 11);
      复制代码

    apply方法

    • 语法:函数名.apply(调用者,[参数1...])
    • 做用:函数被借用时,会当即执行,而且函数体内的this会指向借用者或调用者
    • 代码
    function fn(name, age) {
       this.name = name;
       this.age = age;
     }
    
     // 对象字面量
     var obj = {};
     fn.apply(obj, ['李四', 11]);
    复制代码

    bind方法

    • 语法:函数名.bind(调用者,参数1...)

    • 做用:函数被借用时,不会当即执行,而是返回一个新的函数。须要本身手动调用新的函数。

    • 代码

      function fn(name, age) {
         this.name = name;
         this.age = age;
       }
      
       // 对象字面量
       var obj = {};
       fn.bind(obj, '李四', 11);
      复制代码