by Mariya Diminsky

通过玛丽亚·迪明斯基(Mariya Diminsky)

了解ES6 The Dope Way Part II:Arrow功能和'this'关键字 (Learn ES6 The Dope Way Part II: Arrow functions and the ‘this’ keyword)

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

欢迎来到学习ES6的第二部分, 《 Dope Way》,该系列旨在帮助您轻松理解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?

您可能已经在各处发现了这些看起来很奇怪的埃及象形文字符号,尤其是在其他人的代码中,您正在其中调试“ this”关键字问题。 经过一个小时的修补,现在您正在漫游Google搜索栏并跟踪Stack Overflow。 听起来有点熟?

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

让我们一起涵盖学习ES6 The Dope Way Part II中的三个主题:

  • How the ‘this’ keyword relates to =>.

    ' this '关键字与=>的关系

  • How to migrate functions from ES5 to ES6.如何将功能从ES5迁移到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.

创建箭头函数是为了简化函数范围,并使使用' this '关键字更加直接。 他们利用=& gt; 语法,看起来像箭头。 即使我认为不需要节食,人们也称其为“胖子 ”(Ruby爱好者可能将其称为“哈希摇滚”(hash rock et)),这是需要注意的。

'this'关键字与Arrow功能之间的关系 (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.

在深入研究ES6箭头功能之前,重要的是首先清楚了解ES5代码中“ this ”绑定的内容。

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

如果“ this ”关键字位于对象的方法 (属于对象的函数)内,它将指向什么?

// 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?

现在,如果' this '关键字在方法的函数内部怎么办?

// 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?

嗯,您是否认为“ this ”是指方法的内部功能?

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.

编码长老嗯, 他的代码很强大。 认为'this'关键字绑定到函数确实是很实际的,但事实是,'this'现在已经超出范围……它现在属于……”,他停顿下来,好像遇到了内部动荡,“窗口对象。

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.

为什么“ this ”绑定到窗口对象? 因为' this '总是引用其所在函数的所有者,在这种情况下-因为它现在不在范围内-窗口/全局对象。

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.

当它在对象的方法内部时,函数的所有者就是对象。 因此,“ this ”关键字绑定到对象。 但是,当它位于函数内部时,无论是独立存在还是在另一种方法中,它始终将引用窗口/全局对象。

// 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.

这就是所谓JavaScript怪癖,是指JavaScript中发生的某些事情并不十分简单,并且无法按照您的想法进行工作。 开发人员还认为这是一个糟糕的设计选择,他们现在正在使用ES6的箭头功能进行补救。

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):

在继续之前,重要的是要了解程序员在ES5代码中解决“ this ”问题的两种巧妙方法,尤其是因为您将继续运行ES5一段时间(并非所有浏览器都已完全迁移到ES6):

#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’.

#1在方法的内部函数之外创建一个变量。 现在,“ forEach”方法可以访问“ this ”,从而可以访问对象的属性及其值。 这是因为“ this ”存储在变量中,而它仍在对象的直接方法“ 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.

#2使用bind将引用该方法的' this '关键字附加到该方法的内部函数。

// 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:

现在介绍……箭头功能! 处理“ 这个 ”问题从未如此简单和直接! 简单的ES6解决方案:

// 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.

在ES5中,“ this ”指代函数的父级,而在ES6中,箭头函数使用词法作用域-“ this ”指代当前范围。 因此,内部函数知道仅绑定到内部函数,而不绑定到对象的方法或对象本身。

如何将功能从ES5迁移到ES6。 (How to migrate functions from ES5 to ES6.)

// Before
let bunny = function(name) {console.log("Usagi");
}// After
let bunny = (name) => console.log("Usagi")// Step 1: Remove the word ‘function’.
let bunny = (name) {console.log("Usagi");
}// Step 2: If your code is less than a line, remove brackets and place on one line.
let bunny = (name) console.log("Usagi");// Step 3. Add the hash rocket.
let bunny = (name) => console.log("Usagi");

You did it! Great job! Simple enough right? Here are a few more examples utilizing the fat — er skinny arrow, to get your eyes accustomed:

你做到了! 很好! 很简单吧? 以下是一些使用脂肪的示例-细箭头,使您的眼睛习惯了:

// #1 ES6: if passing one argument you don't need to include parenthesis around parameter.
var kitty = name => name;// same as ES5:
var kitty = function(name) {return name;
};// #2 ES6: no parameters example.
var add = () => 3 + 2;// same as ES5:
var add = function() {return 3 + 2;
};// #3 ES6: if function consists of more than one line or is an object, include braces.
var objLiteral = age => ({ name: "Usagi", age: age });// same as ES5:
var objLiteral = function(age) {return {name: "Usagi",age: age};
};// #4 ES6: promises and callbacks.
asyncfn1().then(() => asyncfn2()).then(() => asyncfn3()).then(() => done());// same as ES5:
asyncfn1().then(function() {asyncfn2();
}).then(function() {asyncfn3();
}).done(function() {done();
});

使用箭头功能时要注意的重要问题 (Important quirks to be aware of when using Arrow functions)

If you use the ‘new’ keyword with => functions it will throw an error. Arrow functions can’t be used as a constructor — normal functions support the ‘new’ via the property prototype and internal method [[Construct]]. Arrow functions don’t use neither, thus the new (() => {}) throws an error.

如果将'new'关键字与=>函数一起使用,则会引发错误。 Arrow函数不能用作构造函数-普通函数通过属性原型和内部方法[[Construct]]支持'new'。 箭头函数不使用它们,因此新的(()=> {})引发错误。

Further quirks to consider:

要考虑的其他问题:

// Line breaks are not allowed and will throw a syntax error
let func1 = (x, y)
=> {return x + y;
}; // SyntaxError// But line breaks inside of a parameter definition is ok
let func6 = (x,y
) => {return x + y;
}; // Works!// If an expression is the body of an arrow function, you don’t need braces:
asyncFunc.then(x => console.log(x));// However, statements have to be put in braces:
asyncFunc.catch(x => { throw x });// Arrow functions are always anonymous which means you can’t just declare them as in ES5:
function squirrelLife() {// play with squirrels, burrow for food, etc.
}// Must be inside of a variable or object property to work properly:
let squirrelLife = () => {// play with squirrels, burrow for food, etc.// another super squirrel action.
}

Congrats! You’ve made it through Learn ES6 The Dope Way Part II and now you have a basis for arrow function knowledge, the lexical benefits it gives to ‘this’ and also snagged yourself some JavaScript quirk skills! :)

恭喜! 您已通过Learn ES6 The Dope Way Part II取得了成功,现在您已经掌握了箭头功能知识,它为' this '带来的词汇好处,并且还掌握了一些JavaScript怪癖技能! :)

Keep your wisdom updated by liking and following as more Learn ES6 The Dope Way is coming soon to Medium!

通过喜欢和关注更多来保持您的智慧更新。 了解ES6涂料之路即将成为中型!

Part I: const, let & var

第一部分:const,let和var

Part II: (Arrow) => functions and ‘this’ keyword

第二部分:(箭头)=>函数和“ this”关键字

Part III: Template Literals, Spread Operators & Generators!

第三部分:模板文字,传播运算符和生成器!

Part IV: Default Parameters, Destructuring Assignment, and a new ES6 method!

第四部分:默认参数,解构分配和新的ES6方法!

Part V: Classes, Transpiling ES6 Code & More Resources!

第五部分:类,转译ES6代码及更多资源!

You can also find me on github ❤ https://github.com/Mashadim

您也可以在github❤https ://github.com/Mashadim上找到我

翻译自: https://www.freecodecamp.org/news/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881/

了解ES6 The Dope Way Part II:Arrow功能和'this'关键字相关推荐

  1. 了解ES6 The Dope Way第三部分:模板文字,扩展运算符和生成器!

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 了解ES6 The Dope Way第三部分:模板文字,扩展运算符和生成器! (Learn ES6 The ...

  2. 了解ES6 The Dope Way第五部分:类,转译ES6代码和更多资源!

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 了解ES6 The Dope Way第五部分:类,转译ES6代码和更多资源! (Learn ES6 The ...

  3. 学习ES6 The Dope Way Part I:const,let&var

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 学习ES6 The Dope Way Part I:const,let&var (Learn ES ...

  4. JS ES6中的箭头函数(Arrow Functions)使用

    转载这篇ES6的箭头函数方便自己查阅. ES6可以使用"箭头"(=>)定义函数,注意是函数,不要使用这种方式定义类(构造器). 一.语法 基础语法 (参数1, 参数2, -, ...

  5. es6+angular1.X+webpack 实现按路由功能打包项目

    需求来源 之前使用jspm来打包项目 但是有个最大的缺点,就是只能把项目打包成一个大的js,当项目开发到后期会很大,网上找了很久也没找到合理的jspm打包方式. 所以开始调研可以打包angular项目 ...

  6. MATLAB GUI设计II 多功能模式题目生成器 四则运算 | 界面切换 | 字符串处理 | cell数组 | GUI

    前言 让我先吐槽一下 _(:△」∠) _ 这个可以用来整人的程序花费了我整整一天多的时间 全内容整整800行代码 生成的pdf说明报告长达26P 总体来说 这个GUI可以实现较多的复杂功能 整体结构我 ...

  7. ES6飞机大战篇-添加子弹追踪功能

    既然是飞机大战 那必定少不了子弹追踪 那么添加子弹追踪功能的实现如下: // 原文链接:https://blog.csdn.net/erweimac/article/details/82256087 ...

  8. es6字符串扩展 -- 字符串长度补全功能 padStart(), padEnd()

    ES2017 引入了字符串补全长度的功能.如果某个字符串不够指定长度,会在头部或尾部补全.padStart()用于头部补全,padEnd()用于尾部补全. 'x'.padStart(5, 'ab') ...

  9. 【ES6基础】Object的新方法

    Object对象可谓是JS的重要核心内容,在你使用JS的过程中,你会发现自己的工作大部分都是在操作对象,ES6.ES7.ES8引入了不少新的方法,本篇文章笔者将带着大家一起熟悉下重点的新方法. 本篇文 ...

最新文章

  1. java web--servlet(2)
  2. MyBatis Generator:代码生成器
  3. TensorFlow2-神经网络训练
  4. 培智计算机教学论文,【培智数学论文】_培智数学教学论文
  5. display 隐藏css,CSS-元素的显示与隐藏
  6. python 英语翻译 excel_Excel自动翻译
  7. 数据库优化---空间换时间优化
  8. python视频补帧_AI 复原 100 年前的京城老视频,靠这三个开源工具
  9. Android 适配器 自定义
  10. [bzoj3202][SDOI2013]项链
  11. 经纬度转GeoHash
  12. 保证只要看一遍,新手也能写出来的超简单五子棋代码
  13. 中国古代数学家张丘建在他的《算经》中提出了一个著名的“百钱百鸡问题”:一只公鸡值五钱,一只母鸡值三钱,三只小鸡值一钱,现在要用百钱买百鸡,请问公鸡,母鸡,小鸡各多少只?
  14. html页面发送微信朋友圈,【源码分享】分享一个基于官方share.html简化的分享js代码(微信,朋友圈,QQ)...
  15. 【SRAM】CubeMX配置STM32H743+IS61WV204816外部扩展SRAM
  16. Unity TTS文字转语音 朗读 基于SpeechLib
  17. 2017美团北京java后台开发
  18. 计算机取证科普性基础
  19. 2019年终职场盘点:如何用5级管理法,经营好自己最重要的资产?
  20. python依据出生日期判断星座(少量代码)

热门文章

  1. iOS架构篇-3 网络接口封装
  2. php column not found,java.sql.SQLException: Column 'cloumn name' not found.
  3. 配置 腾讯云 SSL 证书 SSL证书实现https,环境:phpStudy下Apache环境
  4. 按照文字内容动态设置TableViewCell的高度
  5. jenkins添加git源码目录时报Error performing command错误
  6. 组合与继承之重写方法和字段
  7. 如何居中一个浮动元素?
  8. 提升Hadoop计算能力的并行框架
  9. 如何修改 远程桌面的 默认端口号 3389
  10. 摘自一个读者读后rework的感受