Home >Web Front-end >Front-end Q&A >What is the difference between arrow functions and ordinary functions in es6

What is the difference between arrow functions and ordinary functions in es6

青灯夜游
青灯夜游Original
2022-03-08 12:11:014192browse

Difference: 1. The definition of arrow function is much simpler, clearer and faster than the definition of ordinary function; 2. The arrow function does not create its own this, but the ordinary function does; 3. The arrow function cannot be used as The constructor is used, and the arrow function can be used as a constructor; 4. The arrow function does not have its own arguments, but the arrow function does.

What is the difference between arrow functions and ordinary functions in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

The arrow function is a high-frequency test point in the front-end interview. The arrow function is an API of ES6. I believe many people know it. Because its syntax is simpler than ordinary functions, it is deeply loved by everyone.

1. Basic syntax

In ES6, arrows => are allowed to be used to define arrow functions. The specific syntax is, Let’s look at a simple example:

// 箭头函数
let fun = (name) => {
    // 函数体
    return `Hello ${name} !`;
};

// 等同于
let fun = function (name) {
    // 函数体
    return `Hello ${name} !`;
};

It can be seen that defining arrow functions is much simpler in mathematical syntax than ordinary functions. The arrow function omits the function keyword and uses the arrow => to define the function. The parameters of the function are placed in the brackets before =>, and the function body is placed in the curly braces after =>.

About the parameters of the arrow function:

If the arrow function has no parameters, just write an empty bracket.

If the arrow function has only one parameter, you can also omit the parentheses surrounding the parameter.

If the arrow function has multiple parameters, separate the parameters with commas (,) and wrap them in parentheses.

// 没有参数
let fun1 = () => {
    console.log(111);
};

// 只有一个参数,可以省去参数括号
let fun2 = name => {
    console.log(`Hello ${name} !`)
};

// 有多个参数
let fun3 = (val1, val2, val3) => {
    return [val1, val2, val3];
};

About the function body of the arrow function:

If the function body of the arrow function has only one line of code, it simply returns a variable or Returns a simple JS expression, you can omit the curly braces { } in the function body.

let f = val => val;
// 等同于
let f = function (val) { return val };

let sum = (num1, num2) => num1 + num2;
// 等同于
let sum = function(num1, num2) {
  return num1 + num2;
};

If the function body of the arrow function has only one line of code, which returns an object, it can be written as follows:

// 用小括号包裹要返回的对象,不报错
let getTempItem = id => ({ id: id, name: "Temp" });

// 但绝不能这样写,会报错。
// 因为对象的大括号会被解释为函数体的大括号
let getTempItem = id => { id: id, name: "Temp" };

If The function body of the arrow function has only one statement and does not need to return a value (the most common is to call a function). You can add a voidkeyword

let fn = () => void doesNotReturn();

in front of this statement. The most common arrow function The purpose of is to simplify the callback function.

// 例子一
// 正常函数写法
[1,2,3].map(function (x) {
  return x * x;
});

// 箭头函数写法
[1,2,3].map(x => x * x);

// 例子二
// 正常函数写法
var result = [2, 5, 1, 4, 3].sort(function (a, b) {
  return a - b;
});

// 箭头函数写法
var result = [2, 5, 1, 4, 3].sort((a, b) => a - b);

2. The difference between arrow functions and ordinary functions

##1. The syntax is more concise and clear

As can be seen from the basic syntax examples above, the definition of arrow functions is much simpler, clearer and faster than the definition of ordinary functions.

2. The arrow function will not create its own this (Important!! Understand in depth!!)

Let’s first take a look at the arrow function on MDN

Explanation of this.

The arrow function does not create its own

this, so it does not have its own this, it will only start from the upper level of its own scope chain Inherit this.

The arrow function does not have its own

this, it will capture the # position it is in when definition (note, when it is defined, not when it is called) ##this of the outer execution environment, and inherit this this value. Therefore, the pointing of this in the arrow function is already determined when it is defined, and will never change later. Let’s take a look at an example:

var id = 'Global';

function fun1() {
    // setTimeout中使用普通函数
    setTimeout(function(){
        console.log(this.id);
    }, 2000);
}

function fun2() {
    // setTimeout中使用箭头函数
    setTimeout(() => {
        console.log(this.id);
    }, 2000)
}

fun1.call({id: 'Obj'});     // 'Global'

fun2.call({id: 'Obj'});     // 'Obj'

In the above example, a normal function is used in

setTimeout

in function fun1. When the function is executed after 2 seconds , at this time the function is actually executed in the global scope, so this points to the Window object, and this.id points to the global variable id, so the output is 'Global'. However, setTimeout in function fun2 uses an arrow function. The this of this arrow function is determined when it is defined, and it inherits its outer layer#this in the execution environment of ##fun2, and when fun2 is called, this is changed to the object ## by the call method #{id: 'Obj'}, so 'Obj' is output. Let’s look at another example: <pre class="brush:js;toolbar:false;">var id = &amp;#39;GLOBAL&amp;#39;; var obj = { id: &amp;#39;OBJ&amp;#39;, a: function(){ console.log(this.id); }, b: () =&gt; { console.log(this.id); } }; obj.a(); // &amp;#39;OBJ&amp;#39; obj.b(); // &amp;#39;GLOBAL&amp;#39;</pre>In the above example, the method

a

of object

obj

is defined using an ordinary function, ordinary function When called as a method on an object, this points to the object to which it belongs. Therefore, this.id is obj.id, so 'OBJ' is output. However, method b is defined using an arrow function. this in the arrow function actually inherits this in the global execution environment where it is defined, so Points to the Window object, so 'GLOBAL' is output. (It should be noted here that the curly braces {} that define the object cannot form a separate execution environment, it is still in the global execution environment!!)

3、箭头函数继承而来的this指向永远不变(重要!!深入理解!!)

上面的例子,就完全可以说明箭头函数继承而来的this指向永远不变。对象obj的方法b是使用箭头函数定义的,这个函数中的this永远指向它定义时所处的全局执行环境中的this,即便这个函数是作为对象obj的方法调用,this依旧指向Window对象。

4、.call()/.apply()/.bind()无法改变箭头函数中this的指向

.call()/.apply()/.bind()方法可以用来动态修改函数执行时this的指向,但由于箭头函数的this定义时就已经确定且永远不会改变。所以使用这些方法永远也改变不了箭头函数this的指向,虽然这么做代码不会报错。

var id = &#39;Global&#39;;
// 箭头函数定义在全局作用域
let fun1 = () => {
    console.log(this.id)
};

fun1();     // &#39;Global&#39;
// this的指向不会改变,永远指向Window对象
fun1.call({id: &#39;Obj&#39;});     // &#39;Global&#39;
fun1.apply({id: &#39;Obj&#39;});    // &#39;Global&#39;
fun1.bind({id: &#39;Obj&#39;})();   // &#39;Global&#39;

5、箭头函数不能作为构造函数使用

我们先了解一下构造函数的new都做了些什么?简单来说,分为四步: ① JS内部首先会先生成一个对象; ② 再把函数中的this指向该对象; ③ 然后执行构造函数中的语句; ④ 最终返回该对象实例。

但是!!因为箭头函数没有自己的this,它的this其实是继承了外层执行环境中的this,且this指向永远不会随在哪里调用、被谁调用而改变,所以箭头函数不能作为构造函数使用,或者说构造函数不能定义成箭头函数,否则用new调用时会报错!

let Fun = (name, age) => {
    this.name = name;
    this.age = age;
};

// 报错
let p = new Fun(&#39;cao&#39;, 24);

6、箭头函数没有自己的arguments

箭头函数没有自己的arguments对象。在箭头函数中访问arguments实际上获得的是外层局部(函数)执行环境中的值。

// 例子一
let fun = (val) => {
    console.log(val);   // 111
    // 下面一行会报错
    // Uncaught ReferenceError: arguments is not defined
    // 因为外层全局环境没有arguments对象
    console.log(arguments); 
};
fun(111);

// 例子二
function outer(val1, val2) {
    let argOut = arguments;
    console.log(argOut);    // ①
    let fun = () => {
        let argIn = arguments;
        console.log(argIn);     // ②
        console.log(argOut === argIn);  // ③
    };
    fun();
}
outer(111, 222);

上面例子二,①②③处的输出结果如下:

What is the difference between arrow functions and ordinary functions in es6

很明显,普通函数outer内部的箭头函数fun中的arguments对象,其实是沿作用域链向上访问的外层outer函数的arguments对象。

可以在箭头函数中使用rest参数代替arguments对象,来访问箭头函数的参数列表!!

7、箭头函数没有原型prototype

let sayHi = () => {
    console.log(&#39;Hello World !&#39;)
};
console.log(sayHi.prototype); // undefined

8、箭头函数不能用作Generator函数,不能使用yeild关键字

【相关推荐:javascript视频教程web前端

The above is the detailed content of What is the difference between arrow functions and ordinary functions in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn