原文:https://medium.freecodecamp.org/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881

-----------------------------------------------------------

Welcome to Part II of Learn ES6 The Dope Way, a series created to help you easily understand ES6 (ECMAScript 6)!

So, what the heck is => ?

You’ve probably seen these strange Egyptian-looking hieroglyphics symbols here and there, especially in someone else’s code, where you’re currently debugging a ‘this’ keyword issue. After an hour of tinkering, you’re now roaming the Google search bar and stalking Stack Overflow. Sound familiar?

Together, let’s cover three topics in Learn ES6 The Dope Way Part II:

  • How the ‘this’ keyword relates to =>.
  • How to migrate functions from ES5 to ES6.
  • Important quirks to be aware of when using =>.

Arrow Functions

Arrow functions were created to simplify function scope and make using the ‘this’ keyword much more straightforward. They utilize the => syntax, which looks like an arrow. Even though I don’t think it needs to go on a diet, people call it “the fat arrow” (and Ruby enthusiasts may know it better as the “hash rocket” ) — something to be aware of.

How the ‘this’ keyword relates to Arrow Functions

Before we dive deeper into ES6 arrow functions, it’s important to first have a clear picture of what ‘this’ binds to in ES5 code.

If the ‘this’ keyword were inside an object’s method (a function that belongs to an object), what would it refer to?

 
// Test it here: https://jsfiddle.net/maasha/x7wz1686/
var bunny = {
name: 'Usagi',
showName: function() {
alert(this.name);
}
}; bunny.showName(); // Usagi

  

Correct! It would refer to the object. We’ll get to why later on.

Now what about if the ‘this’ keyword were inside of method’s function?

 
// Test it here: https://jsfiddle.net/maasha/z65c1znn/
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks: function() {
this.tasks.forEach(function(task) {
alert(this.name + " wants to " + task);
});
}
}; bunny.showTasks();
// [object Window] wants to transform
// [object Window] wants to eat cake
// [object Window] wants to blow kisses // please note, in jsfiddle the [object Window] is named 'result' within inner functions of methods.

  

What did you get? Wait, what happened to our bunny…?

 
 

Ah, did you think ‘this’ refers to the method’s inner function?

Perhaps the object itself?

You are wise to think so, yet it is not so. Allow me to teach you what the coding elders had once taught me:

Coding Elder: “Ah yes, the code is strong with this one. It is indeed practical to think that the ‘this’ keyword binds to the function but the truth is, ‘this’ has now fallen out of scope…It now belongs to…”, he pauses as if experiencing inner turmoil, “the window object.

That’s right. That’s exactly how it happened.

Why does ‘this’ bind to the window object? Because ‘this’, always references the owner of the function it is in, for this case — since it is now out of scope — the window/global object.

When it is inside of an object’s method — the function’s owner is the object. Thus the ‘this’ keyword is bound to the object. Yet when it is inside of a function, either stand alone or within another method, it will always refer to the window/global object.

 
// Test it here: https://jsfiddle.net/maasha/g278gjtn/
var standAloneFunc = function(){
alert(this);
} standAloneFunc(); // [object Window]

  

But why…?

This is known as a JavaScript quirk, meaning something that just happens within JavaScript that isn’t exactly straightforward and it doesn’t work the way you would think. This was also regarded by developers as a poor design choice, which they are now remedying with ES6's arrow functions.

Before we continue, it’s important to be aware of two clever ways programmers solve the ‘this’ problem within ES5 code, especially since you will continue to run into ES5 for awhile (not every browser has fully migrated to ES6 yet):

#1 Create a variable outside of the method’s inner function. Now the ‘forEach’ method gains access to ‘this’ and thus the object’s properties and their values. This is because ‘this’ is being stored in a variable while it is still within the scope of the object’s direct method ‘showTasks’.

 
// Test it here: https://jsfiddle.net/maasha/3mu5r6vg/
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks: function() {
var _this = this;
this.tasks.forEach(function(task) {
alert(_this.name + " wants to " + task);
});
}
}; bunny.showTasks();
// Usagi wants to transform
// Usagi wants to eat cake
// Usagi wants to blow kisses

  

#2 Use bind to attach the ‘this’ keyword that refers to the method to the method’s inner function.

 
// Test it here: https://jsfiddle.net/maasha/u8ybgwd5/
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks: function() {
this.tasks.forEach(function(task) {
alert(this.name + " wants to " + task);
}.bind(this));
}
}; bunny.showTasks();
// Usagi wants to transform
// Usagi wants to eat cake
// Usagi wants to blow kisses

  

And now introducing…Arrow functions! Dealing with ‘this’ issue has never been easier and more straightforward! The simple ES6 solution:

 
// Test it here: https://jsfiddle.net/maasha/che8m4c1/

var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks() {
this.tasks.forEach((task) => {
alert(this.name + " wants to " + task);
});
}
}; bunny.showTasks();
// Usagi wants to transform
// Usagi wants to eat cake
// Usagi wants to blow kisses

  

While in ES5 ‘this’ referred to the parent of the function, in ES6, arrow functions use lexical scoping — ‘this’ refers to it’s current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object’s method or the object itself.

Arrow functions and the ‘this’ keyword的更多相关文章

  1. 《理解 ES6》阅读整理:函数(Functions)(四)Arrow Functions

    箭头函数(Arrow Functions) 就像名字所说那样,箭头函数使用箭头(=>)来定义函数.与传统函数相比,箭头函数在多个地方表现不一样. 箭头函数语法(Arrow Function Sy ...

  2. JavaScript ES6 Arrow Functions(箭头函数)

    1. 介绍 第一眼看到ES6新增加的 arrow function 时,感觉非常像 lambda 表达式. 那么arrow function是干什么的呢?可以看作为匿名函数的简写方式. 如: var ...

  3. ES6 In Depth: Arrow functions

    Arrows <script language="javascript"> <!-- document.bgColor = "brown"; ...

  4. ES6学习笔记<二>arrow functions 箭头函数、template string、destructuring

    接着上一篇的说. arrow functions 箭头函数 => 更便捷的函数声明 document.getElementById("click_1").onclick = ...

  5. ES6 箭头函数(Arrow Functions)

    ES6 箭头函数(Arrow Functions) ES6 可以使用 "箭头"(=>)定义函数,注意是函数,不要使用这种方式定义类(构造器). 一.语法 具有一个参数的简单函 ...

  6. arrow functions 箭头函数

    ES6里新增加的,与普通方法不同的地方 1.this 的对象在定义函数的时候确定了,而不是在使用的时候才决定 2.不可以使用 new  ,也就不能当构造函数 3.this 的值一旦确定无法修改     ...

  7. 箭头函数 Arrow Functions/////////////////////zzz

    箭头符号在JavaScript诞生时就已经存在,当初第一个JavaScript教程曾建议在HTML注释内包裹行内脚本,这样可以避免不支持JS的浏览器误将JS代码显示为文本.你会写这样的代码: < ...

  8. ES6箭头函数(Arrow Functions)

    ES6可以使用“箭头”(=>)定义函数,注意是函数,不要使用这种方式定义类(构造器). 一.语法 1. 具有一个参数的简单函数 var single = a => a single('he ...

  9. 深入浅出ES6(七):箭头函数 Arrow Functions

    作者 Jason Orendorff  github主页  https://github.com/jorendorff 箭头符号在JavaScript诞生时就已经存在,当初第一个JavaScript教 ...

随机推荐

  1. 事件触发器-----dispatchEvent

    不要被标题蒙蔽了,今天的重点不是论述事件触发器,而是说一下dispatchEvent这个东西.好了,先简单做个铺垫,dispatchEvent是作为高级浏览器(如chrome.Firfox等)的事件触 ...

  2. iOS图片设置圆角性能优化

    问题 圆角虽好,但如果使用不当,它就是你的帧数杀手,特别当它出现在滚动列表的时候.下面来看圆角如何毁掉你的流畅度的. 实测 layer.cornerRadius 我创建了一个简单地UITableVie ...

  3. Graph database_neo4j 底层存储结构分析(2)

    3       neo4j存储结构 neo4j 中,主要有4类节点,属性,关系等文件是以数组作为核心存储结构:同时对节点,属性,关系等类型的每个数据项都会分配一个唯一的ID,在存储时以该ID 为数组的 ...

  4. spring-boot 速成(7) 集成dubbo

    github上有一个开源项目spring-boot-starter-dubbo 提供了spring-boot与dubbo的集成功能,直接拿来用即可.(记得给作者点赞,以示感谢!) 下面是使用步骤,先看 ...

  5. LINUX下动态链接库的使用-dlopen dlsym dlclose dlerror(转)

    dlopen 基本定义 功能:打开一个动态链接库  包含头文件:  #include <dlfcn.h>  函数定义:  void * dlopen( const char * pathn ...

  6. Windows 2008 R2防火墙设置运行被ping通

    参考文献: http://huobumingbai.blog.51cto.com/1196746/323896/

  7. 爬虫IP被禁的简单解决方法

    爬虫以前听上去好厉害好神秘的样子,用好了可以成就像Google.百度这样的索索引擎,用不好可以凭借不恰当的高并发分分钟崩掉一个小型网站.写到这里想到12306每年扛住的并发请求量,觉得好牛逼. 爬虫和 ...

  8. 《廖雪峰 . Git 教程》学习总结

    基本上,Git就是以下面的命令顺序学习的.文中笔记是从廖雪峰老师的 Git教程 中总结出来的,方面查阅命令. 1.基础 git config --global user.name "Your ...

  9. Git 的 WindowsXP安装

    文章1: http://blog.sina.com.cn/s/blog_5063e4c80100sqzq.html 一.安装必要客户端 1. TortoiseGit http://tortoisegi ...

  10. Windows Phone本地数据库(SQLCE):1、介绍(翻译)(转)

    一只大菜鸟,最近要学习windows phone数据库相关的知识,找到了一些比较简短的教程进行学习,由于是英文的,顺便给翻译了.本身英语水平就不好,估计文中有不少错误,如果有不幸读到的童鞋请保持对翻译 ...