In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "what is the common grammar of es6". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what is the common grammar of es6" can help you solve the problem.
The most commonly used ES6 features let, const
These two uses are similar to var in that they are used to declare variables, but they both have their own special uses in practice.
First, let's take a look at the following example:
Var name = 'zach'while (true) {var name =' obama' console.log (name) / / obama break} console.log (name) / / obama
Using var twice, the output is obama, because ES5 has only global scope and function scope, and no block-level scope, which leads to a lot of unreasonable scenarios. The first scenario is that the inner variable you see now overrides the outer variable. Let, on the other hand, actually adds a block-level scope to JavaScript. The variables declared with it are valid only within the block of code where the let command is located.
Let name = 'zach'while (true) {let name =' obama' console.log (name) / / obama break} console.log (name) / / zach
Another unreasonable scenario brought about by var is that the loop variables used to count are leaked into global variables, as shown in the following example:
Var a = []; for (var I = 0; I
< 10; i++) { a[i] = function () { console.log(i); };}a[6](); // 10 上面代码中,变量i是var声明的,在全局范围内都有效。所以每一次循环,新的i值都会覆盖旧值,导致最后输出的是最后一轮的i的值。而使用let则不会出现这个问题。 var a = [];for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); };}a[6](); // 6 再来看一个更常见的例子,了解下如果不用ES6,而用闭包如何解决这个问题。 var clickBoxs = document.querySelectorAll('.clickBox')for (var i = 0; i < clickBoxs.length; i++){ clickBoxs[i].onclick = function(){ console.log(i) }} 我们本来希望的是点击不同的clickBox,显示不同的i,但事实是无论我们点击哪个clickBox,输出的都是5。下面我们来看下,如何用闭包搞定它。 function iteratorFactory(i){ var onclick = function(e){ console.log(i) } return onclick;}var clickBoxs = document.querySelectorAll('.clickBox')for (var i = 0; i < clickBoxs.length; i++){ clickBoxs[i].onclick = iteratorFactory(i)} const也用来声明变量,但是声明的是常量。一旦声明,常量的值就不能改变。 const PI = Math.PIPI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only 当我们尝试去改变用const声明的常量时,浏览器就会报错。 const有一个很好的应用场景,就是当我们引用第三方库的时声明的变量,用const来声明可以避免未来不小心重命名而导致出现bug: const monent = require('moment')class, extends, super 这三个特性涉及了ES5中最令人头疼的的几个部分:原型、构造函数,继承...你还在为它们复杂难懂的语法而烦恼吗?你还在为指针到底指向哪里而纠结万分吗? 有了ES6我们不再烦恼! ES6提供了更接近传统语言的写法,引入了Class(类)这个概念。新的class写法让对象原型的写法更加清晰、更像面向对象编程的语法,也更加通俗易懂。 class Animal { constructor(){ this.type = 'animal' } says(say){ console.log(this.type + ' says ' + say) }}let animal = new Animal()animal.says('hello') //animal says helloclass Cat extends Animal { constructor(){ super() this.type = 'cat' }}let cat = new Cat()cat.says('hello') //cat says hello 上面代码首先用class定义了一个"类",可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。简单地说,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实力对象可以共享的。 Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。上面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。 super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。 ES6的继承机制,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。 P.S 如果你写react的话,就会发现以上三个东西在最新版React中出现得很多。创建的每个component都是一个继承React.Component的类。详见react文档 arrow function 这个恐怕是ES6最最常用的一个新特性了,用它来写function比原来的写法要简洁清晰很多: function(i){ return i + 1; } //ES5(i) =>I + 1 / / ES6
It's simply outrageous, isn't it?
If the equation is complex, you need to wrap the code in {}:
Function (x, y) {x-ray; y-Murray; return x-ray;} (x, y) = > {x-ray; y-Murray; return x-ray}
In addition to looking more concise, arrow function also has a super-invincible feature!
This objects in the JavaScript language have been a headache for a long time, and you have to be very careful when using this in object methods. For example:
Class Animal {constructor () {this.type = 'animal'} says (say) {setTimeout (function () {console.log (this.type +' says'+ say)}, 1000)}} var animal = new Animal () animal.says ('hi') / / undefined says hi
Running the above code will report an error because the this in setTimeout points to the global object. So in order for it to work correctly, there are two traditional solutions:
The first is to pass this to self, and then use self to refer to this
Says (say) {var self = this; setTimeout (function () {console.log (self.type + 'says' + say)}, 1000)
two。 The second method is to use bind (this), that is
Says (say) {setTimeout (function () {console.log (self.type + 'says' + say)} .bind (this), 1000)
But now that we have the arrow function, we don't have to go to so much trouble:
Class Animal {constructor () {this.type = 'animal'} says (say) {setTimeout (()) = > {console.log (this.type +' says'+ say)}, 1000)} var animal = new Animal () animal.says ('hi') / / animal says hi
When we use the arrow function, the this object in the body of the function is the object in which it is defined, not the object in which it is used. Http://www.jzspfk.com/ of Ningbo Men's Hospital
It is not because there is a mechanism for binding this inside the arrow function, the actual reason is that the arrow function does not have its own this at all, and its this inherits from the outside, so the inner this is the this of the outer code block.
Template string
This thing is also very useful, when we want to insert large chunks of html content into the document, the traditional writing is very troublesome, so we usually refer to some template libraries, such as mustache and so on.
You can look at the following code first:
$("# result") .append ("There are" + basket.count + "+" items in your basket, "+" + basket.onSale + "are on sale!")
We need to use a bunch of'+ 'signs to connect text with variables, and after using ES6's new feature template string ``, we can write it like this:
$("# result") .append (`append ${basket.count} items in your basket, ${basket.onSale} are on sale! `)
Isn't it cool to use backquotes (`) to identify the start, ${} to refer to variables, and all spaces and indents to be retained in the output?!
React Router has also used ES6 syntax since version 1.0.3, such as this example:
{taco.name}
React Router
Destructuring
ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called Destructuring.
Look at the following example:
Let cat = 'ken'let dog =' lili'let zoo = {cat: cat, dog: dog} console.log (zoo) / / Object {cat: "ken", dog: "lili"}
With ES6, you can write something like this:
Let cat = 'ken'let dog =' lili'let zoo = {cat, dog} console.log (zoo) / / Object {cat: "ken", dog: "lili"}
The reverse can be written as follows:
Let dog = {type: 'animal', many: 2} let {type, many} = dogconsole.log (type, many) / / animal 2default, rest
Default is very simple, meaning the default value. You can take a look at the following example. You forgot to pass parameters when calling the animal () method. The traditional practice is to add the sentence type = type | | 'cat' to specify the default value.
Function animal (type) {type = type | | 'cat' console.log (type)} animal ()
If we use ES6, we just write this directly:
Function animal (type = 'cat') {console.log (type)} animal ()
The last rest syntax is also very simple, looking directly at the example:
Function animals (... types) {console.log (types)} animals ('cat',' dog', 'fish') / / ["cat", "dog", "fish"]
If we don't use ES6, we have to use ES5's arguments.
This is the end of the content about "what is the common grammar of es6". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.