美文网首页
箭头函数和this指向

箭头函数和this指向

作者: 名字是乱打的 | 来源:发表于2020-06-04 12:48 被阅读0次
箭头函数基本使用
// 箭头函数: 也是一种定义函数的方式
  // 1.定义函数的方式: function
  const aaa = function () {

  }

  // 2.对象字面量中定义函数
  const obj = {
    bbb() {

    }
  }

  // 3.ES6中的箭头函数
  // const ccc = (参数列表) => {
  //
  // }
  const ccc = () => {

  }

带返回值的箭头函数

// 1.参数问题:
  // 1.1.放入两个参数
  const sum = (num1, num2) => {
    return num1 + num2
  }

  // 1.2.放入一个参数
  const power = num => {
    return num * num
  }

  // 2.函数中
  // 2.1.函数代码块中有多行代码时
  const test = () => {
    // 1.打印Hello World
    console.log('Hello World');

    // 2.打印Hello Vuejs
    console.log('Hello Vuejs');
  }

  // 2.2.函数代码块中只有一行代码
  // const mul = (num1, num2) => {
  //   return num1 + num2
  // }
  const mul = (num1, num2) => num1 * num2
  console.log(mul(20, 30));

  // const demo = () => {
  //   console.log('Hello Demo');
  // }
  const demo = () => console.log('Hello Demo')
  console.log(demo());

什么时候使用箭头

一般我我们准备把一个函数作为参数放在另外一个函数里的时候使用.
比如

setTimeout(function () {
    console.log(this);//打印的this是window
  }, 1000)

 setTimeout(function () {
    console.log(this);//打印的this是window
  }, 1000)
 
  setTimeout(() => {
    console.log(this);//打印的this是window
  }, 1000)

//setTimeout(function () 
//{这种结构其实默认第一个参数是window,所以函数体内向外找到的第一个作用域是window
  const obj = {
    aaa() {
      setTimeout(function () {
        console.log(this); // 打印的this是window
      })
 
      setTimeout(() => {
        console.log(this); //打印的this是 obj对象
      })
    }
  }
 
  obj.aaa()

箭头函数中的this是如何查找的?
答案: 向外逐层查找最近作用域的this.

  const obj = {
    aaa() {
      setTimeout(function () {
        setTimeout(function () {
          console.log(this); // window
        })

        setTimeout(() => {
          console.log(this); // window
        })
      })

      setTimeout(() => {
        setTimeout(function () {
          console.log(this); // window
        })

        setTimeout(() => {
          console.log(this); // obj
        })
      })
    }
  }

  obj.aaa()

相关文章

  • 箭头函数和this指向

    箭头函数基本使用 带返回值的箭头函数 什么时候使用箭头 一般我我们准备把一个函数作为参数放在另外一个函数里的时候使...

  • 箭头函数和 this指向

    箭头函数和普通函数的区别: 首先补一下 this 是什么? this: this 是和执行上下文绑定的,也就是说每...

  • 函数的扩展

    函数的扩展 箭头函数和普通函数区别箭头函数没有this对象,箭头函数的里的this始终指向定义时所在对象,普通函数...

  • 箭头函数和普通函数的主要区别是什么?

    箭头函数和普通函数的主要区别: this的指向问题,箭头函数是不存在this的(也是箭头函数和普通函数最主要的区别...

  • 箭头函数

    引入箭头函数有两个方面的作用:更简短的函数并且不绑定this 普通函数和箭头函数的区别: 箭头函数的this指向规...

  • ES6的箭头函数和普通函数区别

    刚才写下面一段代码时发现bind中this在箭头函数和普通函数指向不一样: 当在箭头函数是this指向window...

  • es6 箭头函数的this指向

    箭头函数在创建时确定了this指向。 下方例子中,箭头函数创建时this指向window,调用时也就指向了window

  • REACT 中事件处理函数传递参数的两种方式

    第一种是箭头函数传参 箭头函数没有this指向,默认是继承外部上下的this,所以箭头函数中的this指向的就是组...

  • 箭头函数

    箭头函数 箭头函数能让this的指向固定化 分析:1)第一个setInterval()中使用了箭头函数,箭头函数使...

  • this指向(箭头函数)

    以this的使用场景进行分类: 1.普通函数下,this 的指向 2.构造函数下,this 的指向 3.箭头函数下...

网友评论

      本文标题:箭头函数和this指向

      本文链接:https://www.haomeiwen.com/subject/kfcgzhtx.html