XiaoKL

Javascript.ReactNative-2-javascript-syntax-in-react-native

JavaScript Syntax in React Native

 

Contents:

Arrow Function

Let+Const 

Default + Rest + Spread

Destructuring assignment

Computed object property names

Classes 

for ... of

Template Strings

Modules

Modules Loader 

Object Short Notation

Object Spread

Function Trailing Comma

Async Functions

 

Reference

 

1. Arrow Function

1.1 Arrow Function的特征

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 };

 

1.2 Arrow function的应用场景

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 

 

To Content List

 

2. Block scoping (Let + Const)

2.1 Introduction to Const and Let 

| 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 }

To Content List 

3. Default + Rest + Spread

3.1 Spread

"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

 

3.2 Rest

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 (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]

 

3.3 Default

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

To Content List 

 

4. Destructuring assignment

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

To Content List 

 

5. Computed object property names

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

To Content List

 

6. Classes

Ref[9]  

6.1 Defining classes

A. class关键字来定义类

B. 先定义类后使用

1 let user = new User(); // User is not a constructor
2 class User {}

  

6.2 Class expressions

"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 };

 

6.3 Class body

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);

 

6.4 Mix-ins

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()

To Content List

 

7. for ... of 

"The for...of statement creates a loop iterating over iterable objects 

(including ArrayMapSetStringTypedArrayarguments object and so on) " Ref[10]

7.1 for ... of vs for ... in

"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 */

 

To Content List

 

8. Template Strings

模版字符串

"Template literals are string literals allowing embedded expressions. They were

called "template strings" in prior editions of the ES2015 / ES6 specification. " Ref[11]

8.1 Introduction 

A. Template literals are enclosed by the back-tick (` `)

B. To escape a back-tick in a template literal, put a backslash before the back-tick.

C. Template literals中占位符(place holder)的形式是: ${expression}

D. place-holder中的表达式以及place-holder之间的文本被传递给函数,默认函数将这些链接成一个字符串

E. If there is an expression preceding the template literal (func here),  the template string is called "tagged template literal".

"In that case, the tag expression (usually a function) gets called with the processed template literal,

which you can then manipulate before outputting. "

1 `string text ${expression} string text`
2 
3 func `string text ${expression} string text`

 

8.2 Multi-line strings

1 console.log(`string text line 1
2 string text line 2`);
3 // "string text line 1
4 // string text line 2"

 

8.3 Expression interpolation

在字符串中插入表达式

1 var a = 5;
2 var b = 10;
3 console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
4 // "Fifteen is 15 and
5 // not 20."

 

 

8.4 Tagged template literals

 

The first argument contains an array of string literals;

The second are the values of the processed (or sometimes called cooked) substitution expressions ("15" and "50" here).

 1 var a = 5;
 2 var b = 10;
 3 
 4 function tag(strings, ...values) {
 5   console.log(strings[0]); // "Hello "
 6   console.log(strings[1]); // " world "
 7   console.log(strings[2]); // ""
 8   console.log(values[0]);  // 15
 9   console.log(values[1]);  // 50
10 
11   return "Bazinga!";
12 }
13 
14 tag`Hello ${ a + b } world ${ a * b }`;
15 // "Bazinga!"

 

Another Example:

 1 function template(strings, ...keys) {
 2   return (function(...values) {
 3     var dict = values[values.length - 1] || {};
 4     console.log(strings);
 5     console.log(keys);
 6     var result = [strings[0]];
 7     // console.log(typeof result);
 8     console.log(result);
 9     keys.forEach(function(key, i) {
10       var value = Number.isInteger(key) ? values[key] : dict[key];
11       result.push(value, strings[i + 1]);
12     });
13     return result.join('');
14   });
15 }
16 
17 var t1Closure = template`${0}--${1}${0}!`;
18 console.log(t1Closure('Y', 'A'));  // "YAY!" 
19 
20 // var t2Closure = template`${0} ${'foo'}!`;
21 // t2Closure('Hello', {foo: 'World'});  // "Hello World!"

8.5 Raw strings

"The special raw property, available on the first function argument of tagged template literals,

allows you to access the raw strings as they were entered."  Ref[11]

 1 function tag(strings, ...values) {
 2   
 3   console.log(`length: ${strings.raw.length}`);
 4   for(var i = 0; i < strings.raw.length; i++) {
 5     console.log(strings.raw[i]);
 6   }
 7 }
 8 
 9 let a = 9;
10 let b = 10;
11 tag `hello \n world ${a+b}!`
12 console.log('------------------------');
13 let c = `hello \n world ${a+b}!`;
14 console.log(c);

 

 

String.raw()

1 var a = 3, b = 2;
2 var c = String.raw`Hi\n${a+b}!`;
3 console.log(c);

 

To Content List

 

9. Modules

 

To Content List

 

10. Modules Loader

 

To Content List

 

11. Object Short Notation

 

To Content List

 

12. Object Spread

ES7 in stage-2

// Rest Properties
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(z); // {"a":3,"b":4}
console.log(x); // 1

// Spread Properties
let c = {x, ...z};
console.log(c); // {"x":1,"a":3,"b":4}

 

To Content List

13. Function Trailing Comma 

ES7 in stage-2

Ref[12]

1 function something(a, 
2 b, 
3 c, // 
4 ) {
5   console.log('trailing commas in function parameter lists');
6 }
7 
8 something(1,2,3);

 

To Content List

 

14. Async Functions

 

To Content List


Reference

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 

 

12. Proposal to allow trailing commas in function parameter lists

https://github.com/jeffmo/es-trailing-function-commas 

 

13. Arrow Function

13.1 arrow function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

13.2 ES6 Arrow Functions: The New Fat & Concise Syntax in JavaScript

https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/

 

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

 

posted on 2016-07-03 00:55  XiaoKL  阅读(402)  评论(0编辑  收藏  举报

导航