标签:
Computed object property names
A: Arrows are a function shorthand using the =>
syntax.
B: expression body and statement body
C: arrows share the same lexical |this|
as their surrounding code.
1 // Expression bodies 2 var odds = evens.map(v => v + 1); 3 var nums = evens.map((v, i) => v + i); 4 5 // Statement bodies 6 nums.forEach(v => { 7 if (v % 5 === 0) 8 fives.push(v); 9 }); 10 11 // Lexical this 12 var bob = { 13 _name: "Bob", 14 _friends: [], 15 printFriends() { 16 this._friends.forEach(f => 17 console.log(this._name + " knows " + f)); 18 } 19 };
A. How To Use ES6 Arrow Functions With React Native
http://moduscreate.com/how-to-use-es6-arrow-functions-with-react-native/
| Function.prototype.bind | 参考: Javascript.learn-javascript-build-in-object-function-apply-call-bind
| const | "In JavaScript, `const` means that the identifier can’t be reassigned. " Ref[2]
`const` is a signal that the identifier won’t be reassigned.
`let` is a signal that the variable may be reassigned.
`var` is not recommended in ES6.
Ref[3]:
1 function f() { 2 { 3 let x; 4 { 5 // okay, block scoped name 6 const x = "sneaky"; 7 // error, const 8 x = "foo"; 9 } 10 // okay, declared with `let` 11 x = "bar"; 12 // error, already declared in block 13 let x = "inner"; 14 } 15 }
"The spread operator (扩展操作符) allows an expression to be expanded in places where multiple arguments
(for function calls) or multiple elements (for array literals) or multiple variables
(for destructuring assignment) are expected." Ref[4]
在函数调用中的使用:
1 // For function calls: 2 myFunction(...iterableObj); 3 4 // For array literals: 5 [...iterableObj, 4, 5, 6] 6 7 8 /////////////////////////////////////////// 9 // apply() 10 function myFunction(x, y, z) { } 11 var args = [0, 1, 2]; 12 myFunction.apply(null, args); 13 14 // spread operator 15 function myFunction(x, y, z) { } 16 var args = [0, 1, 2]; 17 myFunction(...args); 18 19 /////////////////////////////////////////// 20 // Any argument in the argument list can use the spread syntax 21 // and it can be used multiple times. 22 function myFunction(v, w, x, y, z) { } 23 var args = [0, 1]; 24 myFunction(-1, ...args, 2, ...[3]);
在array literal中的使用:
1 // ... can be used anywhere in the array literal and it can be 2 // used multiple times. 3 var parts = [‘shoulders‘, ‘knees‘]; 4 var lyrics = [‘head‘, ...parts, ‘and‘, ‘toes‘]; // ["head", "shoulders", "knees", "and", "toes"] 5 6 // concatenate array 7 var arr1 = [0, 1, 2]; 8 var arr2 = [3, 4, 5]; 9 arr1.push(...arr2);
spread operator (扩展操作符) 只适用iterables(可迭代对象):
1 var obj = {"key1":"value1"}; 2 function myFunction(x) { 3 if (x === ‘undefined‘) { 4 console.log(‘x === undefined is true!‘) 5 } 6 else { 7 console.log(‘x === undefined is false!‘) 8 } 9 console.log(x); // x is ‘undefined‘ 10 } 11 myFunction(...obj); 12 var args = [...obj]; 13 console.log(args, args.length) //[] 0
输出是:
x === undefined is false! [] 0
Rest parameters: "The rest parameter syntax allows us to represent an indefinite number of arguments as an array. " Ref[5]
1 function(a, b, ...theArgs) { 2 // ... 3 }
"If the last named argument of a function is prefixed with ...
, it becomes an array whose elements from 0
(inclusive) to
theArgs.length
(exclusive) are supplied by the actual arguments passed to the function." Ref[5]
Demo:
1 function fun1(...theArgs) { 2 console.log(theArgs.length); 3 } 4 5 fun1(); // 0 6 fun1(5); // 1 7 fun1(5, 6, 7); // 3
1 function multiply(multiplier, ...theArgs) { 2 return theArgs.map(function (element) { 3 return multiplier * element; 4 }); 5 } 6 7 var arr = multiply(2, 1, 2, 3); 8 console.log(arr); // [2, 4, 6]
Default function parameters allow formal parameters to be initialized with default values if no value or undefined
is passed.
1 function multiply(a, b = 1) { 2 return a*b; 3 } 4 5 console.log(multiply(5)); // 5 6 console.log(multiply(5, 3)); // 15
A: Passing undefined
对有默认值的参数传递 ‘undefined‘,则默认值会被使用
1 function logBackgroundColor(element, color = ‘rosybrown‘) { 2 console.log(element, color) 3 } 4 5 logBackgroundColor(‘someDiv‘); // someDiv rosybrown 6 logBackgroundColor(‘someDiv‘, undefined); // someDiv rosybrown 7 logBackgroundColor(‘someDiv‘, ‘blue‘); // someDiv blue
B: Evaluated at call time
参数的默认值在调用时才进行计算
1 function callSomething(thing = something()) { return thing } 2 3 function something(){ 4 let today = Date.now(); 5 console.log(today); 6 return "sth" + today; 7 } 8 9 callSomething(); 10 setTimeout(callSomething, 3000)
C: Default parameters are available to later default parameters
默认参数可以被后面的默认参数引用
1 function singularAutoPlural(singular, plural = singular+"s", 2 rallyingCry = plural + " ATTACK!!!") { 3 return [singular, plural, rallyingCry ]; 4 } 5 6 //["Gecko","Geckos", "Geckos ATTACK!!!"] 7 console.log(singularAutoPlural("Gecko")); 8 9 //["Fox","Chicken", "Chicken ATTACK!!!"] 10 console.log(singularAutoPlural("Fox", "Chicken"));
在默认参数中被使用的function不能是inner function。
1 function f(a = go()) { 2 function go(){return ":P"} 3 } 4 5 // Error: go is not defined 6 f();
function f(a = go()) { console.log(a); } function go(){return ":P"} // :P f();
D: Parameters without defaults after default parameters
1 function f(x=1, y) { 2 return [x, y]; 3 } 4 5 console.log(f()); // [1, null] 6 console.log(f(2)); // [2, null] 7 console.log(f(2,3));// [2, 3]
E: Destructured parameter with default value assignment
1 function f([x, y] = [1, 2], {z: k} = {z: 3}) { 2 return x + y + k; 3 } 4 5 console.log(f()); // 6
Destructuring assignment: 解构化赋值
"Destructuring allows binding using pattern matching, with support for matching arrays and objects.
Destructuring is fail-soft, similar to standard object lookup foo["bar"]
, producing undefined
values when not found." Ref[3]
"The destructuring assignment syntax is a JavaScript expression that makes it possible to
extract data from arrays or objects into distinct variables." Ref[7]
A: 从左边进行赋值,多出的值被忽略
1 var foo = ["one", "two", "three", "four"]; 2 3 var [one, two, three] = foo; 4 console.log(one); // "one" 5 console.log(two); // "two" 6 console.log(three); // "three"
B: 默认值
1 var a, b; 2 3 [a=5, b=7] = [1]; 4 console.log(a); // 1 5 console.log(b); // 7
1 var a, b; 2 3 [a=5, b] = [1]; 4 console.log(a); // 1 5 if (b === undefined) { 6 console.log(‘b is undefined‘); 7 } 8 9 console.log(typeof b);
C: Parsing an array returned from a function
1 function f() { 2 return [1, 2]; 3 } 4 5 var a, b; 6 [a, b] = f(); 7 console.log(a); // 1 8 console.log(b); // 2
1 function f() { 2 return [1, 2, 3]; 3 } 4 5 var [a, , b] = f(); 6 console.log(a); // 1 7 console.log(b); // 3
1 var url = "https://developer.mozilla.org/en-US/Web/JavaScript"; 2 3 var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); 4 console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] 5 6 var [, protocol, fullhost, fullpath] = parsedURL; 7 8 console.log(protocol); // "https"
D: 对象解构化
1 var o = {p: 42, q: true}; 2 var {q, p} = o; 3 4 console.log(p); // 42 5 console.log(q); // true
1 var o = {p: 42, q: true}; 2 var {p: foo, q: bar} = o; 3 4 console.log(foo); // 42 5 console.log(bar); // true
E: 作为函数参数
1 function drawES6Chart({size = ‘big‘, cords = { x: 0, y: 0 }, radius = 25} = {}) { 2 console.log(size, cords, radius); 3 // do some chart drawing 4 } 5 6 drawES6Chart({ 7 cords: { x: 18, y: 30 }, 8 radius: 30 9 }); // big {"x":18,"y":30} 30
F: Nested object and array destructuring
var metadata = { title: "Scratchpad", translations: [ { locale: "de", localization_tags: [ ], last_edit: "2014-04-14T08:43:37", url: "/de/docs/Tools/Scratchpad", title: "JavaScript-Umgebung" }, { title: "JavaScript-China" } ], url: "/en-US/docs/Tools/Scratchpad" }; var { title: englishTitle, translations: [{ title: localeTitle }, {title: localeTitle2}] } = metadata; console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung" console.log(localeTitle2);// "JavaScript-China"
G: For of iteration and destructuring
1 var people = [ 2 { 3 name: "Mike Smith", 4 family: { 5 mother: "Jane Smith", 6 father: "Harry Smith", 7 sister: "Samantha Smith" 8 }, 9 age: 35 10 }, 11 { 12 name: "Tom Jones", 13 family: { 14 mother: "Norah Jones", 15 father: "Richard Jones", 16 brother: "Howard Jones" 17 }, 18 age: 25 19 } 20 ]; 21 22 for (var {name: n, family: { father: f } } of people) { 23 console.log("Name: " + n + ", Father: " + f); 24 } 25 26 // "Name: Mike Smith, Father: Harry Smith" 27 // "Name: Tom Jones, Father: Richard Jones"
H: Pulling fields from objects passed as function parameter
1 function userId({id}) { 2 return id; 3 } 4 5 function whois({displayName: displayName, fullName: {firstName: name}}){ 6 console.log(displayName + " is " + name); 7 } 8 9 var user = { 10 id: 42, 11 displayName: "jdoe", 12 fullName: { 13 firstName: "John", 14 lastName: "Doe" 15 } 16 }; 17 18 console.log("userId: " + userId(user)); // "userId: 42" 19 whois(user); // "jdoe is John"
I: Computed object property names and destructuring
1 let key = ‘name‘; 2 let {[key]:name} = {name:"vitonzhang"}; 3 console.log(name); // vitonzhang
Computed property names
"Starting with ECMAScript 2015 (aka, ES6), the object initializer syntax also supports computed property names.
That allows you to put an expression in brackets []
, that will be computed as the property name. " Ref[8]
1 // Computed property names (ES6) 2 var i = 0; 3 var a = { 4 ["foo" + ++i]: i, 5 ["foo" + ++i]: i, 6 ["foo" + ++i]: i 7 }; 8 9 console.log(a.foo1); // 1 10 console.log(a.foo2); // 2 11 console.log(a.foo3); // 3
Ref[9]
A. class关键字来定义类
B. 先定义类后使用
1 let user = new User(); // User is not a constructor 2 class User {}
"A class expression is another way to define a class. Class expressions can be named or unnamed.
The name given to a named class expression is local to the class‘s body." Ref[9]
1 // unnamed 2 var Polygon = class { 3 constructor(height, width) { 4 this.height = height; 5 this.width = width; 6 } 7 }; 8 9 // named 10 var Polygon = class Polygon { 11 constructor(height, width) { 12 this.height = height; 13 this.width = width; 14 } 15 };
A. The body of a class is the part that is in curly brackets {}
.
B. The bodies of class declarations and class expressions are executed in strict mode.
C. 一个类最多只能有一个Constructor方法,用super访问父类的Constructor方法。
D. The extends
keyword is used in class declarations or class expressions to create a class as a child of another class.
1 // One may also extend traditional function-based "classes": 2 function Animal (name) { 3 this.name = name; 4 } 5 Animal.prototype.speak = function () { 6 console.log(this.name + ‘ makes a noise.‘); 7 } 8 9 class Dog extends Animal { 10 speak() { 11 super.speak(); 12 console.log(this.name + ‘ barks.‘); 13 } 14 } 15 16 var d = new Dog(‘Mitzie‘); 17 d.speak();
E: The static
keyword defines a static method for a class.
F: Prototype methods
getter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
setter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
1 class Polygon { 2 constructor(height, width) { 3 this.height = height; 4 this.width = width; 5 } 6 7 get area() { 8 return this.calcArea(); 9 } 10 11 calcArea() { 12 return this.height * this.width; 13 } 14 } 15 16 const square = new Polygon(10, 10); 17 18 console.log(square.area);
Mixin: "In object-oriented programming languages, a mixin is a class that contains methods for use by other classes
without having to be the parent class of those other classes." Ref[9.2]
"An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible.
A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript" Ref[9]
1 var CalculatorMixin = Base => class extends Base { 2 calc() { 3 console.log("CalculatorMixin->calc()"); 4 } 5 }; 6 7 class Foo { 8 speak() { 9 console.log("Foo->speak()"); 10 } 11 } 12 13 class Bar extends CalculatorMixin(Foo) { 14 speak() { 15 super.speak(); 16 super.calc(); 17 console.log("Bar->speak()"); 18 } 19 } 20 21 let bar = new Bar(); 22 bar.speak(); 23 24 // Foo->speak() 25 // CalculatorMixin->calc() 26 // Bar->speak()
"The for...of
statement creates a loop iterating over iterable objects
(including Array
, Map
, Set
, String
, TypedArray
, arguments object and so on) " Ref[10]
"The for...in
loop will iterate over all enumerable properties of an object.
The for...of
syntax is specific to collections, rather than all objects. " Ref[10]
1 var numbers = [1, 2, 3]; 2 3 numbers.foo = ‘bar‘; 4 5 for (let num in numbers) { 6 console.log(num); 7 } 8 console.log(‘--------------------------‘); 9 for (let num of numbers) { 10 console.log(num); 11 } 12 13 /* 14 0 15 1 16 2 17 foo 18 -------------------------- 19 1 20 2 21 3 22 */
模版字符串
1. https://facebook.github.io/react-native/docs/javascript-environment.html
2. JavaScript ES6+: var, let, or const?
https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#.nbikurm78 (Read Again)
A. "Slay’n the Waste Monster" (youtube.com)
B. BOOK: Learn JavaScript Universal App Development with Node, ES6, & React
3. Learn ES2015
A detailed overview of ECMAScript 2015 features. Based on Luke Hoban‘s es6features repo.
https://babeljs.io/docs/learn-es2015/
http://es6.imsyu.com/chapter6.html (Learn ES2015的中文版本)
4. Spread operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
5. Rest parameters
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
6. Default parameters
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
7. Destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
8. Computed property names
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
9. Classes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
9.1 BOOK: Exploring ES6
http://exploringjs.com/es6/
9.2 Mixin
https://en.wikipedia.org/wiki/Mixin
10. for ... of
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
11. Template literals
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
51. 深入浅出ES6
http://www.infoq.com/cn/es6-in-depth/
X. ES6 online repl
es6 online repl
https://babeljs.io/repl
ES6 Playgrounds: Run and test ECMA Script 6 online, in terminal or using plugins
http://voidcanvas.com/es6-playgrounds-cli-browser-plugins/
Y. ES6-Learning
List of resources to learn ECMAScript 6!
https://github.com/ericdouglas/ES6-Learning
Javascript.ReactNative-2-javascript-syntax-in-react-native
标签:
原文地址:http://www.cnblogs.com/cwgk/p/5632406.html