Bootstrap

js箭头函数和普通函数的区别

1.this(执行上下文)指向

(1)普通函数中的this:

  • 在简单调用中,非严格模式下,指向window。严格模式下,如果this没被指定值,那么才为undefined
function parent() {
    console.log(this);    
}

parent();// window。其实parent()相当于parent.call(window)

'use strict';

function parent() {
   console.log(this);
 
}

 parent(1,2); // undefined
 parent.call(1,2); // this为1
  • 作为某个对象方法调用时,this指向该对象。
  • 当该普通函数被间接调用时,即:使用call()apply()方法调用时,this指向call()和apply()第一个参数。注意:在非严格模式下, 当第一个参数为null或者undefined时,调用函数中的this指向window哦~~~
function parent() {
   console.log(this);
}

 const obj = {
     name: 'ha'
}
        
 parent.call(obj); // this指向obj对象 
  • 该普通函数被用作构造函数用new关键字构造对象实例时,this指向新建的实例。

(2)箭头函数中的this:

  • 没有自己的this,内部this的值,依赖于外部非箭头函数的this。
function regular() {

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

        const obj = {
            name: 'ha'
        }
        
        regular.call(obj );

2.构造函数

(1)普通函数

  • 普通函数可以作为构造函数来用,用new去新建对象实例。

(2)箭头函数

  • 不能当做构造函数去用,并且,会报错。

3.arguments对象

(1)普通函数

  • 普通函数内部,arguments为特殊的类数组对象。包含了函数被调用时的参数列表。

(2)箭头函数

  • 内部是没有arguments对象,同this一样,依赖于外部非箭头函数。
function regular() {

   const arrow = () => {
       console.log(arguments);
       
   }
   arrow();
}


regular(1,2,3);
  • 如果你期待从箭头函数中,获取其全部的参数,可以用剩余参数功能the rest parameters feature),剩余参数必须作为函数参数的最后一个参数:
function regular() {

   const arrow = (...arg) => {
        console.log(arg); // [[1,2,3], 232]
        
    }
    arrow([1,2,3], 232);
}


regular(1,2,3);

4.隐式return

(1)普通函数

  • 用return去返回一个函数的结果。无return语句,或者return后面无表达式,则返回undefined。

(2)箭头函数

  • 如果函数仅有一个表达式,那么该表达式的结果会被隐式返回。
const increment = (num) => num + 1;
increment(41); // => 42

5.当作为回调方法去使用时

(1)普通函数

  • 由于普通函数的this,由执行时候确定。那么当做为定时器函数或者事件监听器的回调去执行时,就有this指向的问题了。这时候,你或许需要用bind()方法去绑定this值。

(2)箭头函数

  • 箭头函数的this,由定义它的时候,外部非箭头函数中this所决定。因此,如果需要将一个函数作为回调函数去执行,并且,不希望函数中的this发生改变时。那么,非箭头函数就是把利器了。
class Hero {
  constructor(heroName) {
    this.heroName = heroName;
  }

  logName = () => {
    console.log(this.heroName);
  }
}

const batman = new Hero('Batman');

setTimeout(batman.logName, 1000);   // after 1 second logs "Batman"

6.注意点

  • 既然箭头函数内部this由外部非箭头函数this决定,那么对箭头函数调用bind等方法去改变,是没有意义的。
;