Among the many great new features of ES6, the arrow function (or big arrow function) is one of them worth paying attention to! It is not only great and cool, it is good Taking advantage of the scope, we can quickly and easily use the technology we used before, reducing a lot of code... but it may be a bit difficult to understand if you don't understand the principle of arrow functions. So, let's take a look at arrows. Function, now!
Execution Environment
You can learn and try it yourself, you can simply copy the sample program code to your browser console Next. Now, it is recommended to use Firefox(22) Developer Tools. Firefox(22) Developer Tools now supports arrow functions. You can also use Google Chrome. If you use Google Chrome, you must do the following two things:
Enter: about:flags in the address bar of Google Chrome, find the "Use experiential JavaScript" option, and enable it.
Add use strict at the beginning of the function, and then test the arrow function in your Google Chrome (tip: please use Google Chrome v38, I was stuck with the browser version at the time Pitfall):
(function(){ "use strict"; // use arrow functions here }());
Fortunately, more and more browsers will support ES6 features. Now that you have completed all the preparations, let’s continue to dive into it!
A new topic
Recently everyone is discussing a topic about ES6: about arrow functions, like this:
=>
New syntax
With the discussion, a new syntax was born:
param => expression
The new syntax is applied to variables. Multiple variables can be declared in expressions. The following is the arrow function Usage mode:
// 一个参数对应一个表达式 param => expression;// 例如 x => x+2; // 多个参数对应一个表达式 (param [, param]) => expression; //例如 (x,y) => (x + y); // 一个参数对应多个表示式 param => {statements;} //例如 x = > { x++; return x;}; // 多个参数对应多个表达式 ([param] [, param]) => {statements} // 例如 (x,y) => { x++;y++;return x*y;}; //表达式里没有参数 () => expression; //例如var flag = (() => 2)(); flag等于2 () => {statements;} //例如 var flag = (() => {return 1;})(); flag就等于1 //传入一个表达式,返回一个对象 ([param]) => ({ key: value }); //例如 var fuc = (x) => ({key:x}) var object = fuc(1); alert(object);//{key:1}
How the arrow function is implemented
We can convert an ordinary function into an arrow function to implement:
// 当前函数 var func = function (param) { return param.split(" "); } // 利用箭头函数实现 var func = param => param.split(" ");
From the above example, we can see that the syntax of the arrow function actually returns a new function, which has a function body and parameters.
Therefore, we can call the function we just created like this:
func("Felipe Moura"); // returns ["Felipe", "Moura"]
Immediate execution function (IIFE)
You can execute it in the immediate function Use arrow functions, for example:
( x => x * 2 )( 3 ); // 6
This line of code generates a temporary function. This function has a formal parameter x, and the return value of the function is x*2. The system will then execute this temporary function immediately, changing 3 Assign a value to the formal parameter The following function:
( (x, y) => { x = x * 2; return x + y; })( 3, "A" ); // "6A"
We have listed some common problems:
The arguments of the temporary function created by the arrow function will not be set:var func = x => {
return x++;
};
The typeofand
instanceof functionscan also check temporary functions normally:
console.log(arguments); // not defined
Putting arrow functions in parentheses is invalid:
func instanceof Function; // true typeof func; // function func.constructor == Function; // true
Although arrow functions will Generate a temporary function, but this temporary function is not a constructor:<pre class='brush:php;toolbar:false;'>// 有效的常规语法
(function (x, y){
x= x * 2;
return x + y;
} (3, "B") );
// 无效的箭头函数语法
( (x, y) => {
x= x * 2;
return x + y;
} ( 3, "A" ) );
// 但是可以这样写就是有效的了:
( (x,y) => {
x= x * 2;return x + y;
} )( 3,"A" );//立即执行函数</pre>
There is also no prototype object:<pre class='brush:php;toolbar:false;'>var instance= new func(); // TypeError: func is not a constructor</pre>
This arrow The scope of the function is somewhat different from that of other functions. If it is not in strict mode, the this keyword points to window. In strict mode, it is undefined. This in the constructor points to the current object instance. If this is within a function of an object, then This points to this object. This may point to a DOM element. For example, when we add an event listening function, the pointing of this may not be very direct. In fact, the pointing of this (not just this variable) variables is based on a rule. To judge: scope flow. Below I will demonstrate how this appears in the event listening function and in the object function:
In the event listening function:
func.prototype; // undefined
In the constructor: document.body.addEventListener('click', function(evt){
console.log(this); // the HTMLBodyElement itself
});
In In this example, if we let the Person.setName function return the Person object itself, we can use it like this:
function Person () { let fullName = null; this.getName = function () { return fullName; }; this.setName = function (name) { fullName = name; return this; }; } let jon = new Person(); jon.setName("Jon Doe"); console.log(jon.getName()); // "Jon Doe" //注:this关键字这里就不解释了,大家自己google,baidu吧。
In an object:
jon.setName("Jon Doe") .getName(); // "Jon Doe"
But when the execution flow (such as using setTimeout ) and the scope change, this will also change.
let obj = { foo: "bar", getIt: function () { return this.foo; } }; console.log( obj.getIt() ); // "bar"
When the setTimeout function changes the execution flow, the point of this will become a global object, or undefine in strict mode, so in the setTimeout function we use other variables to point to this object. , such as self, that, of course no matter what variables you use, you should first assign values to self, that before setTimeout access, or use the bind method, otherwise these variables will be undefined.
This is the time for the arrow function to appear. It can maintain the scope and the point of this will not change.
Let us look at the first example above, here we use the arrow function:
function Student(data){ this.name = data.name || "Jon Doe"; this.age = data.age>=0 ? data.age : -1; this.getInfo = function () { return this.name + ", " + this.age; }; this.sayHi = function () { window.setTimeout( function () { console.log( this ); }, 100 ); } } let mary = new Student({ name: "Mary Lou", age: 13 }); console.log( mary.getInfo() ); // "Mary Lou, 13" mary.sayHi(); // windowAnalysis: In the sayHi function, we use the arrow function, and the current scope is In a method of the student object, the scope of the temporary function generated by the arrow function is also the scope of the sayHi function of the student object. So even if we call the temporary function generated by the arrow function in setTimeout, this in this temporary function is also pointed correctly.
有趣和有用的使用
创建一个函数很容易,我们可以利用它可以保持作用域的特征:
例如我们可以这么使用:Array.forEach()
var arr = ['a', 'e', 'i', 'o', 'u']; arr.forEach(vowel => { console.log(vowel); });
分析:在forEach里箭头函数会创建并返回一个临时函数 tempFun,这个tempFun你可以想象成这样的:function(vowel){ console.log(vowel);}但是Array.forEach函数会怎么去处理传入的tempFunc呢?在forEach函数里会这样调用它:tempFunc.call(this,value);所有我们看到函数的正确执行效果。
//在Array.map里使用箭头函数,这里我就不分析函数执行过程了。。。。 var arr = ['a', 'e', 'i', 'o', 'u']; arr.map(vowel => { return vowel.toUpperCase(); }); // [ "A", "E", "I", "O", "U" ]
费布拉奇数列
var factorial = (n) => { if(n==0) { return 1; } return (n * factorial (n-1) ); } factorial(6); // 720
我们也可以用在Array.sort方法里:
let arr = ['a', 'e', 'i', 'o', 'u']; arr.sort( (a, b)=> a < b? 1: -1 );
也可以在事件监听函数里使用:
// EventObject, BodyElement document.body.addEventListener('click', event=>console.log(event, this));
推荐的链接
下面列出了一系列有用的链接,大家可以去看一看
总结
尽管大家可能会认为使用箭头函数会降低你代码的可读性,但是由于它对作用域的特殊处理,它能让我们能很好的处理this的指向问题。箭头函数加上let关键字的使用,将会让我们JavaScript代码上一个层次!尽量多使用箭头函数,你可以再你的浏览器测试你写的箭头函数代码,大家可以再评论区留下你对箭头函数的想法和使用方案!我希望大家能享受这篇文章,就像你会不就的将来享受箭头函数带给你的快乐.
相关免费学习推荐:js视频教程
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Understand arrow functions and scope in ES6. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
