JS箭头函数简解

1.箭头函数

在这里插入图片描述

作用:简化函数


  // 普通函数
   const fn1 = function () {
     console.log(111);
   }
   
   // 箭头函数
   const fn2 = () => {
     console.log(222);
   }

语法:

  1. 有参数
	const fn3 = (x) => {
	   console.log(x);
	}
	fn3(333)
  1. 只有一个形参时,可省略小括号
	const fn4 = x => {
	  console.log(x);
	}
	fn4(444)
  1. 只有一行代码时,可省略大括号
	const fn5 = x => console.log(x);
	fn5(555)
  1. 只有一行代码时,有返回值,不用写return
	const fn6 = x => x + x;
	console.log(fn6(333));
  1. 可以直接返回一个对象
	const fn = (uname) => ({ uname: uname })
	console.log(fn('555'));

应用: 利用箭头函数求和


   const getSum = (...arr) => {
     let sum = 0
     for (let i = 0; i < arr.length; i++) {
       sum += i
     }
     return sum
   }
   console.log(getSum(1, 2, 3, 4, 5));

2.箭头函数的this

  1. 在箭头函数之前,每一个函数的this取决于这个函数是如何被调用的

    // 在上一层script中找到的this指向window
	const fun1 = () => {   
      console.log(this);  
    }
    fun1()	// window

  1. 箭头函数不会创建自己的this,只会沿用作用域链的上一层this

    // 函数ing在外层对象obj1中没有找到this(obj1是对象,函数里面才有this)
    const obj1 = {
      uname: 'Tom',
      ing: () => {
        console.log(this); 
      }
    }
    obj1.ing()	// window
    
	// 函数nei在他上一层,函数wai里面找到了this(函数里面才有this)
    const obj2 = {
      uname: 'Tom',
      wai: function () {
        let i = 1
        console.log(this);
        const nei = () => {
          console.log(this); 
        }
        ing()
      }
    }
    obj2.wai()	// obj
	// 同样,如果想使用this,不推荐使用箭头函数

3.改变this指向

call()

  • 作用
    1. 调用函数
    2. 改变this指向
  • 第一个参数是需要指向的对象,后面的参数是函数形参依次对应的实参
	const obj = {
	    name: 'Tom'
	}
	function fn(x, y) {
	    console.log(this);	 // {name: 'Tom'}
	    console.log(x + y);	 // 3
	}
	fn.call(obj, 1, 2)

apply()

  • apply()也可以调用函数和改变this指向

  • apply()与call()相比,传入的实参必须是以数组形式

	 const obj = {
	      name: 'Tom'
	 }
	 function fn(x, y) {
	     console.log(this);	 // {name: 'Tom'}
	     console.log(x + y); // 3
	 }
	fn.apply(obj, [1, 2])

bind()

  • bind()也可以改变this指向,但不会调用函数
  • bind()返回值是this指向更改过的函数(原函数this指向不变)
	let that
    const obj = {
      name: 'Tom'
    }
    function fn(x, y) {
      that = this
    }

    fn()
	// 原函数指向 window
    console.log(that);       // window
    const newFunction = fn.bind(obj)
    
	newFunction()
	// 新函数指向 obj
    console.log(that);       // {name: 'Tom'}
	
	fn()
	// 原函数this指向不变,依旧指向 window
	console.log(that);		// window
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值