vue42(es6补充) —— 箭头函数

本文探讨了Vue.js中ES6的箭头函数的使用,包括参数问题的处理,如无参、单参和多参的写法。还介绍了函数体的简写规则,特别是当函数体只有一行代码时的简化形式。此外,文章重点讲解了箭头函数的this指向,指出它如何在外部作用域中查找this定义,这对于在回调函数中保持this的正确指向至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,参数问题

  1. 基本用法: 无参,无返回值
   const fun = (参数列表) => {}
  1. 放入两个参数
  const sum = (num1,num2) => {
      return num1 +  num2 
    }
  1. 放入一个参数(可省略括号)
   const power = num => {
      return num  * num
    }

二、函数体代码简写:

  1. 函数体有多行代码——照常写
 const hi = () => {
      console.log('hello');
      console.log('箭头函数');
    }
  1. 函数体只有一行代码 ——简写
   const mul = (num1,num2) => num1 * num2  // {return num1 * num2}
    const hel = () => console.log('hello') // {console.log('hello')} 返回undefined

箭头函数使用场景: 当想要将一个函数作为参数传给另一个函数时
eg。

 setTimeOut(function(){

   },100)
    setTimeOut(()=>{
       
   },100)

三、this指向

箭头函数的this: 向外层作用域中一层层查找,直到有this的定义

setTimeOut(function(){
	console.log(this) //window
},100)

setTimeOut(()=>{
	console.log(this)  //window
},100)

const obj = {
	aaa(){
		setTimeOut(function(){
			console.log(this) // window
		},100)

		setTimeOut(()=>{
			console.log(this) // aaa
		},100)
	}
}
const obj = {
      aaa() {
        setTimeout(function () {
          console.log('yi', this); // window
          
          setTimeout(function () {
            console.log('yi1', this); // window
          }, 100)

          setTimeout(() => {
            console.log('yi2', this); // window
          }, 100);
        }, 100)

        setTimeout(() => {
          console.log('er', this); // aaa
          
          setTimeout(function () {
            console.log('er1', this); // window--
          }, 100)

          setTimeout(() => {
            console.log('er2', this); // aaa
          }, 100);
        }, 100);
      }
    }
    obj.aaa();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值