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.

 // Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i); // Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
}); // Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
};

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

 function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// okay, declared with `let`
x = "bar";
// error, already declared in block
let x = "inner";
}
}

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]

在函数调用中的使用:

 // For function calls:
myFunction(...iterableObj); // For array literals:
[...iterableObj, 4, 5, 6] ///////////////////////////////////////////
// apply()
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args); // spread operator
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args); ///////////////////////////////////////////
// Any argument in the argument list can use the spread syntax
// and it can be used multiple times.
function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

在array literal中的使用:

 // ... can be used anywhere in the array literal and it can be
// used multiple times.
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"] // concatenate array
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

spread operator (扩展操作符) 只适用iterables(可迭代对象):

 var obj = {"key1":"value1"};
function myFunction(x) {
if (x === 'undefined') {
console.log('x === undefined is true!')
}
else {
console.log('x === undefined is false!')
}
console.log(x); // x is 'undefined'
}
myFunction(...obj);
var args = [...obj];
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]

 function(a, b, ...theArgs) {
// ...
}

"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:

 function fun1(...theArgs) {
console.log(theArgs.length);
} fun1(); //
fun1(5); //
fun1(5, 6, 7); //
 function multiply(multiplier, ...theArgs) {
return theArgs.map(function (element) {
return multiplier * element;
});
} var arr = multiply(2, 1, 2, 3);
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.

 function multiply(a, b = 1) {
return a*b;
} console.log(multiply(5)); //
console.log(multiply(5, 3)); //

A: Passing undefined

对有默认值的参数传递 'undefined',则默认值会被使用

 function logBackgroundColor(element, color = 'rosybrown') {
console.log(element, color)
} logBackgroundColor('someDiv'); // someDiv rosybrown
logBackgroundColor('someDiv', undefined); // someDiv rosybrown
logBackgroundColor('someDiv', 'blue'); // someDiv blue

B: Evaluated at call time

参数的默认值在调用时才进行计算

 function callSomething(thing = something()) { return thing }

 function something(){
let today = Date.now();
console.log(today);
return "sth" + today;
} callSomething();
setTimeout(callSomething, 3000)

C: Default parameters are available to later default parameters

默认参数可以被后面的默认参数引用

 function singularAutoPlural(singular, plural = singular+"s",
rallyingCry = plural + " ATTACK!!!") {
return [singular, plural, rallyingCry ];
} //["Gecko","Geckos", "Geckos ATTACK!!!"]
console.log(singularAutoPlural("Gecko")); //["Fox","Chicken", "Chicken ATTACK!!!"]
console.log(singularAutoPlural("Fox", "Chicken"));

在默认参数中被使用的function不能是inner function。

 function f(a = go()) {
function go(){return ":P"}
} // Error: go is not defined
f();
function f(a = go()) {
console.log(a);
} function go(){return ":P"} // :P
f();

D: Parameters without defaults after default parameters

 function f(x=1, y) {
return [x, y];
} console.log(f()); // [1, null]
console.log(f(2)); // [2, null]
console.log(f(2,3));// [2, 3]

E: Destructured parameter with default value assignment

 function f([x, y] = [1, 2], {z: k} = {z: 3}) {
return x + y + k;
} console.log(f()); //

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: 从左边进行赋值,多出的值被忽略

 var foo = ["one", "two", "three", "four"];

 var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"

B: 默认值

 var a, b;

 [a=5, b=7] = [1];
console.log(a); //
console.log(b); //
 var a, b;

 [a=5, b] = [1];
console.log(a); //
if (b === undefined) {
console.log('b is undefined');
} console.log(typeof b);

C: Parsing an array returned from a function

 function f() {
return [1, 2];
} var a, b;
[a, b] = f();
console.log(a); //
console.log(b); //
 function f() {
return [1, 2, 3];
} var [a, , b] = f();
console.log(a); //
console.log(b); //
 var url = "https://developer.mozilla.org/en-US/Web/JavaScript";

 var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] var [, protocol, fullhost, fullpath] = parsedURL; console.log(protocol); // "https"

D: 对象解构化

 var o = {p: 42, q: true};
var {q, p} = o; console.log(p); //
console.log(q); // true
 var o = {p: 42, q: true};
var {p: foo, q: bar} = o; console.log(foo); // 42
console.log(bar); // true

E: 作为函数参数

 function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
} drawES6Chart({
cords: { x: 18, y: 30 },
radius: 30
}); // 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

 var people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith"
},
age: 35
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones"
},
age: 25
}
]; for (var {name: n, family: { father: f } } of people) {
console.log("Name: " + n + ", Father: " + f);
} // "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

H: Pulling fields from objects passed as function parameter

 function userId({id}) {
return id;
} function whois({displayName: displayName, fullName: {firstName: name}}){
console.log(displayName + " is " + name);
} var user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
}; console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"

I: Computed object property names and destructuring

 let key = 'name';
let {[key]:name} = {name:"vitonzhang"};
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]

 // Computed property names (ES6)
var i = 0;
var a = {
["foo" + ++i]: i,
["foo" + ++i]: i,
["foo" + ++i]: i
}; console.log(a.foo1); //
console.log(a.foo2); //
console.log(a.foo3); //

To Content List

6. Classes

Ref[9]

6.1 Defining classes

A. class关键字来定义类

B. 先定义类后使用

 let user = new User(); // User is not a constructor
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]

 // unnamed
var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
}; // named
var Polygon = class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

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.

 // One may also extend traditional function-based "classes":
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise.');
} class Dog extends Animal {
speak() {
super.speak();
console.log(this.name + ' barks.');
}
} var d = new Dog('Mitzie');
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

 class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
} get area() {
return this.calcArea();
} calcArea() {
return this.height * this.width;
}
} const square = new Polygon(10, 10); 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]

 var CalculatorMixin = Base => class extends Base {
calc() {
console.log("CalculatorMixin->calc()");
}
}; class Foo {
speak() {
console.log("Foo->speak()");
}
} class Bar extends CalculatorMixin(Foo) {
speak() {
super.speak();
super.calc();
console.log("Bar->speak()");
}
} let bar = new Bar();
bar.speak(); // Foo->speak()
// CalculatorMixin->calc()
// 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]

 var numbers = [1, 2, 3];

 numbers.foo = 'bar';

 for (let num in numbers) {
console.log(num);
}
console.log('--------------------------');
for (let num of numbers) {
console.log(num);
} /*
0
1
2
foo
--------------------------
1
2
3
*/

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. "

 `string text ${expression} string text`

 func `string text ${expression} string text`

8.2 Multi-line strings

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

8.3 Expression interpolation

在字符串中插入表达式

 var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// 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).

 var a = 5;
var b = 10; function tag(strings, ...values) {
console.log(strings[0]); // "Hello "
console.log(strings[1]); // " world "
console.log(strings[2]); // ""
console.log(values[0]); //
console.log(values[1]); // return "Bazinga!";
} tag`Hello ${ a + b } world ${ a * b }`;
// "Bazinga!"

Another Example:

 function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
console.log(strings);
console.log(keys);
var result = [strings[0]];
// console.log(typeof result);
console.log(result);
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
} var t1Closure = template`${0}--${1}${0}!`;
console.log(t1Closure('Y', 'A')); // "YAY!" // var t2Closure = template`${0} ${'foo'}!`;
// 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]

 function tag(strings, ...values) {

   console.log(`length: ${strings.raw.length}`);
for(var i = 0; i < strings.raw.length; i++) {
console.log(strings.raw[i]);
}
} let a = 9;
let b = 10;
tag `hello \n world ${a+b}!`
console.log('------------------------');
let c = `hello \n world ${a+b}!`;
console.log(c);

String.raw()

 var a = 3, b = 2;
var c = String.raw`Hi\n${a+b}!`;
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); // // 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]

 function something(a,
b,
c, //
) {
console.log('trailing commas in function parameter lists');
} 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

Javascript.ReactNative-2-javascript-syntax-in-react-native的更多相关文章

  1. React-Native(三):React Native是基于React设计的

    React Native是基于React js设计的. 参考:<React 入门实例教程> React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript ...

  2. react-native —— 在Windows下搭建React Native Android开发环境

    在Windows下搭建React Native Android开发环境 前段时间在开发者头条收藏了 @天地之灵_邓鋆 分享的<在Windows下搭建React Native Android开发环 ...

  3. React-Native(六):React Native完整的demo项目

    该项目在http://www.lcode.org/study-react-native-opensource-two/上发现 更有意思的发现这个网站https://juejin.im/是采用vue.j ...

  4. React-Native(五):React Native之Text学习

    本章节主要学习Text的布局,仿照网易新网: 代码: /** * Sample React Native App * https://github.com/facebook/react-native ...

  5. React-Native(四):React Native之View学习

    React Native实现以下布局效果:携html5(http://m.ctrip.com/html5/) 基于HelloWord修改项目代码: /** * Sample React Native ...

  6. React-Native(二):React Native开发工具vs code配置

    从网上翻阅了一些开发react-native的开发工具时,发现其实可选的工具还是比较多的Sublime Text,WebStrom,Atom+Nuclide,vs code 等.因为我用.net生态环 ...

  7. React-Native(一):React Native环境搭建

    第一步:安装jdk 从java官网下载jdk8 配置环境变量: JAVA_HOME:D:\Program Files\Java\jdk1.8.0_111 Path中追加:%JAVA_HOME%\bin ...

  8. react-native —— 在Mac上配置React Native Android开发环境排坑总结

    配置React Native Android开发环境总结 1.卸载Android Studio,在终端(terminal)执行以下命令: rm -Rf /Applications/Android\ S ...

  9. 带你从零学ReactNative开发跨平台App开发[react native SqlLite 终极运用](十二)

    ReactNative跨平台开发系列教程: 带你从零学ReactNative开发跨平台App开发(一) 带你从零学ReactNative开发跨平台App开发(二) 带你从零学ReactNative开发 ...

  10. 带你从零学ReactNative开发跨平台App开发-[react native 仿boss直聘](十三)

    ReactNative跨平台开发系列教程: 带你从零学ReactNative开发跨平台App开发(一) 带你从零学ReactNative开发跨平台App开发(二) 带你从零学ReactNative开发 ...

随机推荐

  1. linux mail 使用外部邮箱地址发邮件

    centos 61.系统yum安装的mailx会默认使用本地sendmail发送邮件,这样要求本地的机器必须安装和启动Sendmail服务,配置麻烦,而且会带来不必要的资源占用.通过修改配置文件可以使 ...

  2. html5 placeholder ie 不兼容问题 解决方案

    解决HTML5 placeholder的方案 来源:   时间:2013-09-05 20:06:49   阅读数:11375 分享到: 0 [导读] 使低版本浏览器支持Placeholder有很多方 ...

  3. 浅述python中argsort()函数的用法

    由于想使用python用训练好的caffemodel来对很多图片进行批处理分类,学习过程中,碰到了argsort函数,因此去查了相关文献,也自己在python环境下进行了测试,大概了解了其相关的用处, ...

  4. rabbitMQ+yii2 使用

    安装rabbitMQ 见此文章 http://www.cnblogs.com/zxxyx/p/6229613.html 安装好之后 出现此目录: 然后需要yii里面进行载入: 这个目录下面: 加上这个 ...

  5. Mac Aria2 使用Privoxy将socks代理转化为http代理

    安装Privoxy 打开终端安装privoxy来实现这里我是通过brew来进行的安装 brew install privoxy 看到这行已经安装成功 ==> Caveats To have la ...

  6. 【Shell脚本】怎样表示一个for循环

    [Shell脚本]怎样表示一个for循环 在此说一下我常用的两个结构: 1. for i in $(seq 1 100); do         echo $i done 2. for (( i = ...

  7. 服务器控件中使用<%#...>, JS和html控件中使用<%=...>

    //在服务器控件的属性中,需要用<%#...>来绑定其他控件的ID, 并且要在页面初始方法中,执行Page.DataBind(); <asp:ImageButton ID=" ...

  8. windows下手动安装和配置xamarin

    安装xamarin xamarin官方给出了两种安装方式,自动安装和手动安装. 自动安装比较简单,到http://xamarin.com/download下载xamarininstaller.exe ...

  9. SDRAM的主要参数

    (1) 容量.SDRAM的容量经常用XX存储单元×X体×每个存储单元的位数来表示.例如某SDRAM芯片的容量为4M×4×8bit,表明该存储器芯片的容量为16 M字节.或128 M bit. (2) ...

  10. mysql - 其它

    1.mysql查看表字段和字段描述 SELECT column_name, column_comment FROM information_schema.columns WHERE table_sch ...