In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the new features of JavaScript in ES6". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Current implementation of ES.next
You can view the ECMAScript summarized by Juriy Zaytsev
6 compatibility table, and Mozilla's ES6 implementation page and by using the latest version of modern browsers such as Chrome
Canary, Firefox
Aurora) to learn what ES.next features have been implemented so far.
In Canary, remember to enter chrome:flags and turn on the 'enable experimental JavaScript' option to activate all the latest JavaScript features.
In addition, many ES.next features can be experienced using Google's Traceur transformation compiler (here are some examples of unit tests), as well as some shim projects such as ES6-Shim and Harmony
Collections has also implemented a number of new features.
Use the-- harmony command line option in Node.js (V8) to turn on some experimental ES.next features, including block scope, WeakMap, and so on.
Module
We are used to splitting our code into more manageable functional blocks. In ES.next, a module is a module declaration and a set of code contained in that declaration. Modules can be declared inline (inline), or an external module file can be introduced. An inline module called Car is written roughly as follows:
Module Car {
/ / Import …
/ / Export …
}
An example of a module is a valued module that has been linked to other modules or has lexically encapsulated data. The following is an example of a module example:
Module myCar at "car.js"
Module declarations can be used in the following context:
Module UniverseTest {}
Module Universe {module MilkyWay {}}
Module MilkyWay = 'Universe/MilkyWay'
Module SolarSystem = Universe.MilkyWay.SolarSystem
Module MySystem = SolarSystem
An export declaration declares a local function or variable that can be seen by other modules.
Module Car {
/ / Internal variables
Var licensePlateNo = '556-343'
/ / expose external variables and functions
Export function drive (speed, direction) {
Console.log ('details:', speed, direction)
}
Export module engine {
Export function check () {}
}
Export var miles = 5000
Export var color = 'silver'
}
A module can import any other module it needs using import. The import module reads all the exportable data of the imported module (such as drive (), miles, etc.), but cannot modify them. Exported variables or functions can be renamed.
Again using the export-related example above, we can now selectively import some functions in the module.
For example, we can import drive ():
Import drive from Car
You can also import both drive () and miles:
Import {drive, miles} from Car
Next, we will talk about the concept of module loader API. The module loader allows us to dynamically load the scripts we need. Similar to import, we can use everything declared in export in the imported module.
/ / Signature: load (moduleURL, callback, errorCallback)
Loader.load ('car.js', function (car) {
Console.log (car.drive (500, 'north'))
}, function (err) {
Console.log ('Error:' + err)
});
Load () accepts three parameters:
ModuleURL: a string that represents a module URL (such as "car.js")
Callback: a callback function that accepts module loading, compilation, and output after execution
ErrorCallback: a callback function called when an error occurs during loading or compilation
About classes (class)
I'm not going to talk too much about classes in ES.next in this article, if you want to know how classes and modules will relate, Alex
Russell once wrote a good example to illustrate this.
Having classes in JavaScript does not mean that turning JavaScript into classes in Java.ES.next is just another way to declare semantics (such as functions, prototypes) that we are already familiar with.
Here is the ES.next code that defines a widget:
Module widgets {
/ /...
Class DropDownButton extends Widget {
Constructor (attributes) {
Super (attributes)
This.buildUI ()
}
BuildUI () {
This.domNode.onclick = function () {
/ /...
}
}
}
}
Here's what happens after de-sugared, which is the method we're using right now:
Var widgets = (function (global) {
/ /...
Function DropDownButton (attributes) {
Widget.call (this, attributes)
This.buildUI ()
}
DropDownButton.prototype = Object.create (Widget.prototype, {
Constructor: {value: DropDownButton}
BuildUI: {
Value: function (e) {
This.domNode.onclick = function (e) {
/ /...
}
}
}
});
}) (this)
The way ES.next is written does make the code more readable. Class here is the equivalent of function, at least one thing we do with function. If you are accustomed to and like to use functions and prototypes in JavaScript, don't worry about this future syntax candy.
How do these modules work with AMD?
Is the module in ES.next a step in the right direction? Maybe it is。 My own opinion is that it is one thing to read the relevant specification documents, but quite another to use them. In Harmonizr,Require
You can experience the new module syntax in HM and Traceur, and you will be very familiar with these syntax, which may feel a bit like Python (such as import statement).
In my opinion, if some features are widely used (such as modules), then the platform (that is, browsers) should support them natively. And I'm not the only one who feels that way. James Burke, the man who invented AMD and RequireJS, once said:
I think AMD and RequireJS should be eliminated. They do solve a real problem, but ideally, languages and runtime environments should have similar functions built in. Native support for modules should be able to cover 80% of RequireJS usage requirements, at this point, we no longer need to use any userland module loading libraries, at least in browsers.
But James questioned whether ES.next 's module was a good enough solution. In June, he talked about some of his thoughts on modules in ES.next, ES6.
Modules: Suggestions for improvement and a later article, Why
Not AMD?.
Isaac Schlueter also wrote some of his own ideas some time ago, talking about the shortcomings of the module of ES6. Try the following options and see what you think.
Compatible with Module implementation of current engine
Traceur
Demo
Harmonizr
Require
HM
ES6
Module Loader
Object.observe ()
With Object.observe, we can observe the specified object and be notified when the object is modified. This modification includes the addition, update, deletion and reconfiguration of attributes.
Property observation is a behavior we often see in MVC framework. It is an important component of data binding. Both AngularJS and Ember.js have their own solutions.
This is a very important new feature. It not only performs better than similar implementations of all current frameworks, but also makes it easier to observe pure native objects.
/ / A simple object can be used as a module
Var todoModel = {
Label: 'Default'
Completed: false
}
/ / We observe this object.
Object.observe (todoModel, function (changes) {
Changes.forEach (function (change, I) {
Console.log (change)
/ *
Which attribute has been changed? Change.name
What is the type of change? Change.type
What is the new property value? Change.object [change.name]
, /
});
});
/ / when in use:
TodoModel.label = 'Buy some more milk'
/ *
The label property has been changed
Changing the type is the update of the attribute value
The current property value is' Buy some more milk'
, /
TodoModel.completeBy = '01Compact 2013'
/ *
The completeBy property has been changed
Change the type so that the attribute is added
The current property value is' 01Uniplex 2013'.
, /
Delete todoModel.completed
/ *
The completed property has been changed
Change the type so that the property is deleted
The current property value is undefined
, /
Object.observe will be implemented in Chrome Canary soon (you need to turn on the "enable experimental JavaScript" option).
Compatible with Object.observe () implementation of the current engine
Special version of Chromium
Watch.JS can achieve similar functions, but it is not a polyfill or shim that implements Object.observe
Rick Waldron's article has a more detailed introduction to Object.observe.
Translator's note: Firefox has a similar thing a long time ago: Object.prototype.watch.
Default parameter valu
Default parameter value (Default
The purpose of parameter values) is to initialize some parameters with default initialization values when they are not explicitly passed. This means that we no longer need to write statements like options = options | | {};.
The grammatical form is to assign an initial value to the corresponding parameter name:
Function addTodo (caption ='Do something') {
Console.log (caption)
}
AddTodo (); / / Do something
Formal parameters with default parameter values can only be placed on the far right of the formal parameter list:
Function addTodo (caption, order = 4) {}
Function addTodo (caption ='Do something', order = 4) {}
Function addTodo (caption, order = 10, other = this) {}
Browser that has implemented this feature: Firefox 18 +
Translator's note: Firefox 15 has implemented the default parameter values. The author only said that 18 supports 18, not that 18 is the first supported version. There is this problem, including chrome 24 +, which will be mentioned below in this article.
Block level scope
Block-level scope introduces two new forms of declaration, which can be used to define a variable or constant that exists only in a statement block. The two new declaration keywords are:
Let: syntax is very similar to var, but the defined variables only exist in the current statement block
Const: similar to let, but declares a read-only constant
Using let instead of var makes it easier to define a local variable that only exists in a statement block without worrying about conflicts with variables of the same name in other parts of the function body. Variables declared with var inside let statements are no different from variables declared with var outside let statements. They both have functional scope, not block-level scope.
Translator's note: in case the reader does not understand, I will use an example to explain the above sentence, which goes like this:
Let (var1 = 1) {alert (var1); / / popup 1 is a block-level scope variable var var2 = 2;} var var3 = 3 let alerts (var2); / / pop-up 2, although var2 is declared inside the let statement, it is still a function-scoped variable because it uses the var declaration alert (var3); / / pop-up 3alert (var1); / / throws an exception
Var x = 8
Var y = 0
Let (x = xx 10, y = 12) {
Console.log (xroomy); / / 30
}
Console.log (x + y); / / 8
Browsers to implement let: Firefox 18, Chrome 24 +
Browsers to implement const: Firefox 18 browser, Chrome 24 browser, Safari 6 browser, WebKit, Opera 12 +
Translator's note: Firefox supported let and const a long time ago, but these two old implementations are based on the current ES4 draft. It is somewhat different from the current ES6 draft, for example, the constants declared with const in ES4 do not have block-level scope (like var, but the values are immutable), and let also has some nuances, so forget it. Since few people use the old Firefox (but my main browser is FF3.6!), even if there is a conflict between ES6 and ES4 in the future, we can basically ignore it.
Map
I think most readers are already familiar with the concept of mapping, because we used to use pure objects to implement mapping. map allows us to map a value to a unique key, and then we can get the corresponding value through this key without worrying about the problems caused by prototype inheritance when implementing mapping with ordinary objects.
Using the set () method, you can add a new key-value pair to the map, and using the get () method, you can get the stored value. The Map object has three other methods:
Has (key): a Boolean value indicating whether a key exists in map
Delete (key): delete the key specified in map
Size (): returns the number of key-value pairs in map
Let m = new Map ()
M.set ('todo',' todo'.length); / / "todo" → 4
M.get ('todo'); / / 4
M.has ('todo'); / / true
M.delete ('todo'); / / true
M.has ('todo'); / / false
Browser that has implemented Map: Firefox 18 +
Nicholas Zakas's article has a more detailed introduction to Map.
Compatible with Map implementation of current engine
ES6
Shim
Harmony
Collections
Translator's note: I have translated this article by Nicholas: ECMAScript
Collection types in 6, part two: Map.
The author may not know that in the October ES6 draft, both Map.prototype.size and Set.prototype.size changed from the size () method to the size accessor property. At the same time, there are many new methods added to the Map object, clear () is used to empty a map,forEach () to traverse a map, as well as items (), keys (), values (), etc. Set objects are also similar, there are many methods that the author did not mention, I will not point out the following Set section.
In addition, in ES5, in order to prevent problems caused by prototype inheritance when using objects as mappings (for example, in twitter, @ _ _ proto__ can make browsers jam), you can use var hash = Object.create (null) instead of var hash = {}
Set
As Nicholas Zakas said in his article, Set is nothing new to programmers who have come into contact with other languages such as Ruby and Python, but it is a feature that has been missing in JavaScript.
Any type of data can be stored in a set, but each value can only be stored once (cannot be repeated). Using Set, you can easily create an ordered list that does not contain any duplicate values.
Add (value)-add a value to the set.
Delete (value)-removes the value value from set.
Has (value)-returns a Boolean value indicating whether the value value exists in the set.
Let s = new Set ([1,2,3]); / / s has 1,2
3. Three elements.
S.has (- Infinity); / / false
S.add (- Infinity); / / s has 1,2,3
-four elements of Infinity.
S.has (- Infinity); / / true
S.delete (- Infinity); / / true
S.has (- Infinity); / / false
One of the functions of Set objects is to reduce the complexity of filtering operations (filter methods). For example:
Function unique (array) {
Var seen = new Set
Return array.filter (function (item) {
If (! seen.has (item)) {
Seen.add (item)
Return true
}
});
}
The complexity of this function, which uses Set for array deduplication, is O (n). However, the complexity of other existing array deduplication methods is almost O (n ^ 2).
Browsers that have implemented Set: Firefox 18, Chrome 24.
Nicholas Zakas's article has a more detailed introduction to Set.
Compatible with Set implementation of current engine
ES6
Shim
Harmony
Collections
Translator's note: I have translated this article by Nicholas: ECMAScript
Collection types in 6, part one: Set.
If I were to implement an array deduplication function under ES6, I would write:
Function unique (array) {return [v for (v of Set (array))]}
This function uses for-of traversal in ES6 and array deduction. However, it is slightly less efficient than the above method of removing weights using filter. This function can already be executed in the latest version of Firefox.
In addition, there is a simpler and more efficient way to write it with the help of the Array.from method that will be mentioned below:
> Array.from (new Set ([1, 1, 2, 2, 3, 4]); [1, 2, 2, 3, 4]
It is even possible, with the help of the spread operation in ES6:
> [. New Set ([1, 1, 2, 2, 3, 4])]; [1, 2, 3, 4] WeakMap
The WeakMap key can only be an object value, and the key holds a weak reference to the referenced object to prevent memory leaks. This means that if an object has no reference other than the WeakMap key, the garbage collector destroys the object.
Another feature of WeakMap is that we can't traverse its keys, while Map can.
Let m = new WeakMap ()
M.set ('todo',' todo'.length); / /
Exception, the key must be an object value!
/ / TypeError: Invalid value used as weak map key
M.has ('todo'); / /
It's also abnormal!
/ / TypeError: Invalid value used as weak map key
Let wmk = {}
M.set (wmk, 'thinger'); / / wmk →' thinger'
M.get (wmk); / / 'thinger'
M.has (wmk); / / true
M.delete (wmk); / / true
M.has (wmk); / / false
Browsers that have implemented WeakMap: Firefox 18, Chrome 24.
Compatible with WeakMap implementation of current engine
Harmony
Collections
Nicholas Zakas's article has a more detailed introduction to WeakMap.
Translator's note: I have translated this article by Nicholas: ECMAScript
Collection types in 6, part III: WeakMap
Agent
The Proxy API allows you to create an object whose property values are dynamically calculated at run time. You can also use the proxy API to hook in other objects to achieve functions such as printing records and assignment audits.
Var obj = {foo: "bar"}
Var proxyObj = Proxy.create ({
Get: function (obj, propertyName) {
Return 'Hey,' + propertyName
}
});
Console.log (proxyObj.Alex); / / "Hey, Alex"
You can take a look at Nicholas Zakas's article and this example.
Browsers that implement proxy API: Firefox 18, Chrome 24 +
Translator's note: what the author does not know is that there have been two proposals for acting API, one of which is the old Catch-all
Proxies, one is the new direct agent (Direct)
Proxies). The former has been abandoned. The difference between the two is here. V8 (Chrome and Node.js) implements the former, while Firefox18 and later versions implement the latter (17 and previous versions implement the former). The article Nicholas wrote in 2011 should also be out of date.
Some new APIObject.is
Object.is is a function used to compare whether two values are equal. The main difference between this function and = = is in the comparison between the special value NaN and itself and between positive and negative zeros. The result of Object.is is that NaN is equal to another NaN, and + 0 and-0 are not equal.
Object.is (0,-0); / / false
Object.is (NaN, NaN); / / true
0 =-0; / / true
NaN = NaN; / / false
Realize the browser of Object.is: Chrome 24+
Compatible with Object.is implementation of current engine
ES6
Shim
Translator's note: the difference between the Object.is method and the strict equality = = operator is reflected in the ES standard is the difference between the SameValue algorithm and the strict equality comparison algorithm.
Translator's note: if I understand this BE tweet correctly, Object.is will change its name to Object.sameValue.
Array.from
Array.from: converts array-like objects in parameters (such as arguments, NodeList, DOMTokenList (classList attribute is this type) and NamedNodeMap (attributes property is this type) into an array and returns, such as converting a pure object:
Array.from ({
0: 'Buy some milk'
1:'Go running'
2: 'Pick up birthday gifts'
Length: 3
});
Another example is to convert a collection of DOM nodes:
Var divs = document.querySelectorAll ('div')
Array.from (divs)
/ / [,]
Array.from (divs) .forEach (function (node) {
Console.log (node)
});
That's all for "what are the new features of JavaScript in ES6?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.