Zi 字媒體
2017-07-25T20:27:27+00:00
Arrow function
ECMAScript:6
箭頭函式(Arrow function) 是 Javascript ES6 中一種比 function 更簡短的語法。不一樣的是,它沒有自己的 this、arguments、super、new.target 等語法。
箭頭函式比較常用來當 非方法 的函式,例如一次性的資料 parser。
基本語法
Arrow function 的語法是由一組 () 和 => 所組成( (param1, param2, …, paramN) => { statements } )。
與一般 Function 比較
let str = [
'Hello',
'Johnson',
'How are you?',
'Fine, thank you'
];
// Function
console.log(str.map(function (obj) {
return obj.length;
}));
// [ 5, 7, 12, 15 ]
// Arrow function
console.log(str.map(str => str.length));
// [ 5, 7, 12, 15 ]
其他寫法
let say;
// 基本用法
say = (message) => {
return 'Johnson, ' + message;
};
console.log(say('Hello'));
// 只有一行 statements 時不需要加上 {} 和 return
say = (message) => 'Johnson, ' + message;
console.log(say('Hi'));
// 只有一個參數時可以不用加 ()
say = message => 'Johnson, ' + message;
console.log(say('No ()'));
// 沒有參數時一定要有 ()
say = () => 'XDDDDDD';
console.log(say());
this 的定義
在 Arrow function 是沒有 this 的,因此在使用時需要非常注意。
this 的差異
let obj = {
name: 'Obj Name',
getNameUseFun: function () {
// Obj Name
console.log(this.name);
},
getNameUseArrow: () => {
// undefined
console.log(this.name);
}
};
obj.getNameUseFun();
obj.getNameUseArrow();
Categories: JavaScript
Tags: javascript
分類
Android
AngularJS
API Blueprint
Chrome
Database
MySQL
DataStructure
Docker
Editor
Vim
Firefox
Git
GitLab
Google API
Hadoop
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
PHP
Laravel
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋關鍵字:
寫了
5860316篇文章,獲得
23313次喜歡