【前端面试题】箭头函数中this指向问题


一、技术博客、视频

技术博客:ES6中箭头函数VS普通函数的this指向

视频:
1.箭头函数和this的指向问题(coderwhy老师)
2.箭头函数和this指向问题(尚硅谷老师)

二、实例

// 1.this是静态的,this始终指向函数声明时所在作用域下的this的值
  // 如函数是在全局下定义的,则this指向window

  function getName() {
    console.log(this.name);
  }

  let getName2 = () => {
    console.log(this.name);
  }

  // 设置window对象的name属性
  window.name = "我是全局"
  const others = {
    name: "我是对象"
  }

  // 直接调用
  getName();//输出“我是全局”
  getName2();//输出“我是全局”

// call方法调用,call方法可以改变函数内部的值
  getName.call(others)//输出“我是对象”
  getName2.call(others)//输出“我是全局”,
//箭头函数的this是静态的,无论怎么改变值,this始终指向声明函数时的this值,如函数是在全局下定义的,则this指向window

(1)hello是全局函数,没有直接调用它的对象,也没有使用严格模式,this指向window

function hello() { 
   console.log(this);  // window 
}  
hello();

(2)hello是全局函数,没有直接调用它的对象,但指定了严格模式('use strict'),this指向undefined

function hello() { 
   'use strict';
   console.log(this);  // undefined
}  
hello();

(3)hello直接调用者是obj,第一个this指向obj,setTimeout里匿名函数没有直接调用者,this指向window

const obj = {
    num: 10,
   hello: function () {
    console.log(this);    // obj
    setTimeout(function () {
      console.log(this);    // window
    });
   }    
}
obj.hello();

(4)hello直接调用者是obj,第一个this指向obj,setTimeout箭头函数,this指向最近的函数的this指向,即也是obj

const obj = {
    num: 10,
   hello: function () {
    console.log(this);    // obj
    setTimeout(() => {
      console.log(this);    // obj
    });
   }    
}
obj.hello();

(5)diameter是普通函数,里面的this指向直接调用它的对象obj。perimeter是箭头函数,this应该指向上下文函数this的指向,这里上下文没有函数对象,就默认为window,而window里面没有radius这个属性,就返回为NaN。

const obj = {
  radius: 10,  
  diameter() {    
      return this.radius * 2
  },  
  perimeter: () => 2 * Math.PI * this.radius
}
console.log(obj.diameter())    // 20
console.log(obj.perimeter())    // NaN


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM