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!
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!
Recently everyone is discussing a topic about ES6: about arrow functions, like this:
=>
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}
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"]
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:
var func = x => { return x++; };
and
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:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;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><div class="contentsignin">Copy after login</div></div>
There is also no prototype object:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false">var instance= new func(); // TypeError: func is not a constructor</pre><div class="contentsignin">Copy after login</div></div>
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
document.body.addEventListener('click', function(evt){ console.log(this); // the HTMLBodyElement itself });
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(); // window
创建一个函数很容易,我们可以利用它可以保持作用域的特征:
例如我们可以这么使用: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!