JavaScript ES6 — write less, do more (es6)

JavaScript ES6 brings new syntax and new awesome features to make your code more modern and more readable. It allows you to write less code and do more. ES6 introduces us to many great features like arrow functions, template strings, class destruction, Modules… and more. Let’s take a look.
(JavaScript ES6带来了新的语法和令人敬畏的新功能,使您的代码更现代,更易读。 它使您可以编写更少的代码并做更多的事情。 ES6向我们介绍了许多很棒的功能,例如箭头功能,模板字符串,类破坏,模块等。 让我们来看看。)

const and let
const is a new keyword in ES6 for declaring variables. const is more powerful than var. Once used, the variable can’t be reassigned. In other words, it’s an immutable variable except when it used with objects.
(“const”是ES6中用于声明变量的新关键字。“const”比“var”更强大。一旦使用,变量就不能被重新赋值。换句话说,除非与对象一起使用,否则它是不可变的变量。)
This is really useful for targeting the selectors. For example, when we have a single button that fires an event, or when you want to select an HTML element in JavaScript, use const instead of var. This is because var is ‘hoisted’. It’s always preferable to use const when don’t want to reassign the variable .
(这对于定位选择器非常有用。 例如,当我们有一个触发事件的按钮时,或者您要在JavaScript中选择HTML元素时,请使用“ const”而不是“ var”。 这是因为“ var”已“变量提升”。 当不想重新分配变量时,最好使用const。)

//es5
var myBtn = document.getElementById('mybtn');
//es6
const myBtn = doucmnet.getElementById('mybtn');

In the code above, const will not change and cannot be reassigned. If you try to give it a new value, it will return you an error.

let name = 'said'';
	name = 'rick';
	console.log(name);
	//output -->rick;

let can be reassigned and take new value. It creates a mutable variable.
(可以重新分配let并采用新值。 它创建一个可变变量。)
let is the same as const in that both are blocked-scope. It means that the variable is only available within its scope.
(“ let”与“ const”相同,因为两者都是块作用域。 这意味着该变量仅在其作用域内可用。)

Arrow functions
The arrow function is really awesome, and makes your code more readable, more structured, and look like modern code. Instead of using this:
(箭头功能确实很棒,它使您的代码更具可读性,更结构化,并且看起来像现代代码。 而不是使用此:)

//es5
function myFunc(name){
	return 'hello'+name;
}
console.log(myFunc('said'));
//output 
//hello said

Use this:

//es6 arrow function
const myFunc = name =>{
	return `hi ${name}`
}
console.log(myFunc('said'));  //output hi said;

or even without using arrow or implement `return` keyword

const myFunc = name => `hi ${name}`;

As you see, the arrow function seems more readable and clean! You won’t need to use the old syntax anymore.
Also, you can use Arrow function with map, filter, and reduce built-in functions.
在这里插入图片描述
The map function with arrows looks more clear and readable than map in ES5. With ES6 you can write shorter and smarter code. You can use the same with filter and reduce.

Template Literals
(模板常量)
Template literals or template strings are pretty cool. We don’t have to use the plus (+) operator to concatenate strings, or when we want to use a variable inside a string.
(模板文字或模板字符串非常酷。 我们不必使用加号(+)运算符来连接字符串,也不必在字符串中使用变量时使用。)
The old syntax:
在这里插入图片描述
With new ES6 syntax:
在这里插入图片描述
So simple! It’s a really huge difference between the old syntax and ES6. When playing with strings, the literal string in ES6 looks more organized and well structured than ES5.
(很简单! 旧语法和ES6之间确实有很大的不同。 使用字符串时,与ES5相比,ES6中的文字字符串看起来更具组织性和结构性。)

Default parameters
(默认参数)
When I work in PHP, I usually use default parameters. These allow you to define a parameter in advance.
So, when you forget to write the parameter, it won’t return an undefined error because the parameter is already defined in the default. So when you run your function with a missed parameter, it will take the value of the default parameter t, and it will not return an error!
Look at this example:
在这里插入图片描述
The function above returns undefined, because we forgot to give it the second parameter age.

But if we used the default parameter, it won’t return undefined, and it will use its value when we forget to assign a parameter!
在这里插入图片描述
As you see, the function returns a value even though we missed the second parameter. Now with the default parameter we can handle the error in advance.
(如您所见,即使我们错过了第二个参数,该函数也会返回一个值。 现在,使用默认参数,我们可以提前处理错误。)

Array and object destructing
Destruction makes the assignment of the values of an array or object to the new variable easier.
(变量销毁使得将数组或对象的值分配给新变量更加容易)
The old syntax:
在这里插入图片描述
With ES6 syntax:
在这里插入图片描述
With ES5, we have to assign each value to each variable. With ES6, we just put our values within curly brackets to get any property of the object.
(使用ES5,我们必须将每个值分配给每个变量。 使用ES6,我们只需将值放在大括号中即可获取对象的任何属性。)

Note: if you assign a variable that is not identical to the name of property, it will return undefined. For example, if the name of the property is name and we assign it to a username variable, it will return undefined.
(注意:如果您分配的变量与属性名称不同,则它将返回未定义。 例如,如果属性的名称是name,并且我们将其分配给username变量,则它将返回undefined。)

We always have to name the variable the same as the name of the property. But in case we want to rename the variable, we can use the colon : instead.
(我们总是必须将变量的名称与属性的名称相同。 但是如果要重命名变量,可以使用冒号:代替。)
在这里插入图片描述
For the array, we use the same syntax as the object. We have just to replace the curly brackets with square brackets.
(对于数组,我们使用与对象相同的语法。 我们只需将花括号替换为方括号即可。)
在这里插入图片描述
Import and export
Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.
(在JavaScript应用程序中使用importexport使其更强大。 它们使您可以创建单独的可重用组件。)

If you are familiar with any JavaScript MVC framework, you will see that they use import and export to handle the components most of the time. So how do they really work?
(如果您熟悉任何JavaScript MVC框架,您将看到它们大多数时候使用importexport来处理组件。 那么它们如何真正起作用?)

It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.
(很简单! export允许您导出要在另一个JavaScript组件中使用的模块。 我们使用import导入该模块以在组件中使用它。)

For example, we have two files. The first is named detailComponent.js and the second is named homeComponent.js.
In detailComponent.js we are going to export the detail function.
在这里插入图片描述
And if we want to use this function in homeComponent.js, we will just use import.
在这里插入图片描述
If we want to import more than one module, we just put them within curly brackets.
(如果要导入多个模块,只需将它们放在大括号中即可。)
在这里插入图片描述
So cool, isn’t it?!

Promises
Promises are a new feature of ES6. It’s a method to write asynchronous code. It can be used when, for example, we want to fetch data from an API, or when we have a function that takes time to be executed. Promises make it easier to solve the problem, so let’s create our first Promise!
在这里插入图片描述
If you log your console, it will return a Promise. So, if we want to execute a function after data is fetched, we will use a Promise. The Promise takes two parameters: resolve and reject to handle an expected error.

Note: the fetch function returns a Promise itself !

const url='https://jsonplaceholder.typicode.com/posts';
const getData=(url)=>{
return fetch(url);
}
getData(url).
then(data=> data.json()).
then(result=> console.log(result));

Now if you log your console it will return an array of data.

Rest parameter and Spread operator
在这里插入图片描述
在这里插入图片描述
The spread operator has the same syntax as the rest parameter, but the spread operator takes the Array itself and not just the arguments. We can use the Spread parameter to get the values of an Array, instead of using a for loop or any other method.

const arr=['said',20,'JavaScript enthusiast','Hi','Said','How are you?'];
const Func=(...anArray)=>{
return anArray;
}
console.log(Func(arr));
//output  ["said", 20, "JavaScript enthusiast", "Hi", "Said", "How are you?"

Classes
Classes are the core of object oriented programming (OOP). They make your code more secure and encapsulated. Using classes gives your code a nice structure and keeps it oriented.
(类是面向对象编程(OOP)的核心。 它们使您的代码更加安全和封装。 使用类为您的代码提供了一个不错的结构,并使其保持定向。)
在这里插入图片描述
To create a class, use the class keyword followed by the name of the class with two curly brackets.
(要创建一个类,请使用“ class”关键字,后跟带有两个大括号的类的名称。)
在这里插入图片描述
Now we can access the class methods and properties using the new keyword.
(现在我们可以使用关键字new来访问class方法和属性。)

class myClass{
    constructor(name,age){
    this.name=name;
    this.age=age;
}
}
const Home= new myClass("said",20);
console.log(Home.name)//  said

To inherit from another class, use the extends keyword followed by the name of the class you want to inherit from.
(要从另一个类继承,请使用extends关键字,后跟要继承的类的名称。)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值