了解ES6 The Dope Way Part II:Arrow功能和'this'关键字
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/
相关文章:

[转载]Matlab之静态文本多行输出
转载文章,原文链接:Matlab中的静态文本框中显示多行内容 有时候,我们在GUI中利用静态文本框显示程序的结果,但是结果很长,一行未必可以显示的开,而静态文本框不像edit或listbox那样通过滚动条来显示多行内容…

1-Swift中的Struct 和 Class
1 为什么swift 推荐使用struct类型 在swift中是推荐使用struct类型的,值类型的变量在赋值的时候会自动进行一次低消耗的值拷贝 对比与对象的拷贝更加高效且不存在线程安全问题。 2 Struct 的概述 Swift语言中非常重视结构体,把结构体作为实现面向对象…

rwkj 1422搜索(素数环)
算法分析与设计:搜索(素数环) 时间限制(普通/Java):1000MS/3000MS 运行内存限制:65536KByte 总提交:178 测试通过:35 描述 将1-n这n个数摆成一个环,要求相邻的两个数的和是一个素数,编程输出所有可…

不断的困惑:为什么我仍然使用JavaScript函数语句
Back in the late 90’s — when I learned JavaScript — we were taught to write the “Hello World” function using a function statement. Like this…上世纪90年代后期(当我学习JavaScript时),我们被教导使用函数语句编写“ Hello World”函数。 像这样… …

Tif文件合并类
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq;namespace Common {/// <summary>/// Title Tif文件合并类/// Author:ward/// </…

ubuntu /boot 空间清理
本文引用自 blog.csdn.net/yypony/article/details/17260153方法: 1: 在终端下察看已经安装的旧的内核: ctrlaltt——>进入终端——>输入命令:dpkg --get-selections|grep linux给 /boot文件目录分配空间的时候,…

Swift default参数
swift 支持默认参数,在声明方法的时候,可以给某个参数制定一个默认的使用值,当没有传入值的时候,使用默认的参数,当传入值存在的时候,使用对应的传入值 import UIKitvar str "Hello, playground&quo…

vs2017 open从v_宣布#Open2017,这是面向开发人员的除夕直播流
vs2017 open从vHere are a few reasons to stay home this New Year’s Eve:这是除夕之夜留在家里的一些理由: It’s the worst day of the year for fatal drunk driving deaths 这是致命的酒后驾车致死的一年中最糟糕的一天 It’s crowded 拥挤 It’s freaking c…

Laravel Predis Error while reading line from the server.
问题 Laravel说明文档中的 Redis 发布与订阅案例,命令行运行php artisan redis:subscribe 到60s自动断开并报错 [Predis\Connection\ConnectionException]Error while reading line from the server. [tcp://127.0.0.1:6379]解决 在config/database.php配置文件中&a…

android 带边框的圆角按钮
新建buttonstyle.xml 代码如下 <?xml version"1.0" encoding"UTF-8"?> <layer-list xmlns:android"http://schemas.android.com/apk/res/android"> <!-- 连框颜色值 --><item> <shape> <solid andr…

Swift 字面量表达
字面量是一个很强大的特性,对于缩短代码很有帮助 // // 1 字面量就是 简洁明了指出自己的类型并且为变量赋值的的值 // tom false 称之为字面量 let dog:String "tom"; let ok false;// Array 和 Dictionary 赋值的时候也是使用的字面量 let animals:Ar…

韩国文档的编码方式_像韩国学生学习英语一样学习编码
韩国文档的编码方式by Stephen Mayeux斯蒂芬马约(Stephen Mayeux) 像韩国学生学习英语一样学习编码 (Learn to code like a Korean student learns English) If this is the first you’ve heard of me, then there’s only one thing you need to know: I am an ESL Teacher …

mysql乱码解决
在 /etc/my.cnf加上下面二句: skip-character-set-client-handshakecharacter-set-server utf8转载于:https://www.cnblogs.com/sweetXiaoma/p/6170979.html

LoaderManager使用具体解释(三)---实现Loaders
这篇文字将介绍Loader<D>类,而且介绍自己定义Loader的实现。这是本系列的第三篇文章。一:Loaders之前世界二:了解LoaderManager三:实现Loaders四:实例:AppListLoader重中之重,假设你还没有…

Swift 条件编译,编译标记
1 swift 中的条件编译跟OC中的形式是相同的 #if DEBUGself.navigationView.backgroundColor Color_ff3b30;#elseself.navigationView.backgroundColor Color_main;#endif条件可以接受 os(MacOS) ,参数iOS tvOS等平台 arch(),参数为平台架构组合 arm64 ,i386 swift(),参数为版…

代码简介:向圣诞老人和他的精灵学习Google Analytics(分析)
Here are three stories we published this week that are worth your time:这是我们本周发布的三个值得您关注的故事: Learn Google Analytics from Santa and his elves: 12 minute read 向圣诞老人和他的精灵学习Google Analytics(分析): 阅读12分钟…

生物信息大数据数据库(NCBI、EBI、UCSC、TCGA)
想系统的学习生信数据库可以先看一下北大的公开课,有一章专门讲的数据库与软件: 1-生物信息学:导论与方法 北大\10 生物信息数据库及软件资源 一个优秀的生信开发者能够解决如下问题: 如何鉴定一个重要的且没有被解决的生物学问题…

Dispatch 执行ABC任务,执行完成之后刷新UI,指定任务D
在swift中分组管理异步任务的方式 1 group enter 和 leave 进行同步管理 func method1() {// 创建一个组 ,要是在一个控制器中去规划请求顺序,则这个组要是全局的组let group DispatchGroup();let queue DispatchQueue.global();//let imgsArr [&qu…

关于页游垂直同步的若干问题
这个问题要从人眼感觉抖动的原因来分析第一种情况是常说的屏幕撕裂,就是垂直同 步的事情,可以简单理解为显存的数据更新跟屏幕的绘制刷新缺少同步,一次屏幕刷新的结果可能是多次显存更新的片段集合,这种情况只能使用更接近垂直同步…

javascript函数式_JavaScript中的函数式编程—结合实际示例(第1部分)
javascript函数式by rajaraodv通过rajaraodv JavaScript中的函数式编程—结合实际示例(第1部分) (Functional Programming In JavaScript — With Practical Examples (Part 1)) Functional Programming(FP) can change the way you program for the better. But it’s hard t…
简介子窗口控件(api)
子窗口控件 壹佰软件开发小组 整理编译 回忆第七章的CHECKER程序。这些程序显示了矩形网格。当您在一个矩形中按下鼠标按键时,该程序就画一个x;如果您再按一次鼠标按键,那么x就消失。虽然这个程序的CHECKER1和CHECKER2版本只使用一个主窗口…

【MongoDB学习之一】初始MongoDB
环境 MongoDB4.0 win7_x64 CentOS6.5_x64 一、MongoDB简介 (1)MongoDB使用C开发。 (2)MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。 (3)MongoDB 将数据存储为一个文档。MongoDB是一个基于分布式文件存储的数据库。 (4)MongoDB使用BSON作为数据存储…

swift 和 oc中检测textfield是否输入数字
iOS 开发中用来检测输入框是否输入的是纯数字 Swift 版本 // 代理方法func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {//判断输入的是否是数字 否则无效var cs CharacterSet();// 获取除…

开源项目贡献者_如何吸引新的贡献者加入您的开源项目
开源项目贡献者by Shubheksha通过Shubheksha 如何吸引新的贡献者加入您的开源项目 (How to attract new contributors to your open source project) It’s hard to attract contributors to your FOSS project — especially contributors who are new to open source.很难吸…

滑动轮播图实现最后一张图片无缝衔接第一张图片
原理:使用insertBefore和insertAfter方法调整图片顺序。 测试:firefox/chrome/IE11正常 已知不足:每次播放均使用了一次insertBefore和insertAfter,可考虑在最后一张图的时候将前几张图片整体后移。以后有空再优化。 1、HTML结构 …

一个完整的Installshield安装程序实例—艾泽拉斯之海洋女神出品(三) --高级设置一...
一个完整的Installshield安装程序实例—艾泽拉斯之海洋女神出品(三) --高级设置一 原文:一个完整的Installshield安装程序实例—艾泽拉斯之海洋女神出品(三) --高级设置一上一篇:一个完整的安装程序实例—艾泽拉斯之海…

数据结构,堆和栈和队列的概念
数据结构,堆和栈和队列的概念 1 什么是数据结构 数据结构是计算机存储,组织数据的反复改。数据结构是指相互之间存在的一种或多种特定关系的数据元素集合。 2 数据结构的逻辑结构 1 集合结构,元素都是孤立存在的 2 线性结构 ,…

电子白板 矢量 编码_当涉及白板编码采访时,请记住准备
电子白板 矢量 编码by Andy Tiffany通过安迪蒂芙尼(Andy Tiffany) 当涉及白板编码采访时,请记住准备 (When it comes to whiteboard coding interviews, remember to PREP) PREP is a mnemonic I created to help you remember the steps involved in solving whit…

机器学习实战笔记(Python实现)-03-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为《机器学习实战》学习笔记,内容整理自书本,网络以及自己的理解,如有错误欢迎指正。 源码在Python3.5上测试均通过,代码及…

SQLite.swift的简单使用
使用cocoapod 来进行引入 pod ‘SQLite.swift’ // // SQLiteTool.swift // CreateLectureForSwift // // Created by coder on 2019/6/25. // Copyright © 2019 AlexanderYeah. All rights reserved. // import Foundation import SQLite // id let id Expression(“…