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

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

模版字符串

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

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

时间: 2024-10-04 03:55:19

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

[ReactNative入门到精通]React Native 第一个程序 Hello Word

人生没有对错,只有选择后的坚持,不后悔,走下去,就是对的. React Native 项目目录解析 上一节我们简单的新建了一个React Native的项目AwsoneProject,我们什么都没有操作,就直接在模拟器上运行起来了.这里我们详细的看看,React Native给我们生成的这几个文件到底是做什么用的. 项目目录结构 文件建构如下图所示: android android 的项目构建目录 ios iphone 的项目构建目录 node_modules react native 所引用的

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

React Native是基于React js设计的. 参考:<React 入门实例教程> React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设 Instagram 的网站.做出来以后,发现这套东西很好用,就在2013年5月开源了. 由于 React 的设计思想极其独特,属于革命性创新,性能出众,代码逻辑却非常简单.所以,越来越多的人开始关注和使用,认为它可能是将来 Web 开发的主流工具. 这个项目

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

配置React Native Android开发环境总结 1.卸载Android Studio,在终端(terminal)执行以下命令: rm -Rf /Applications/Android\ Studio.app rm -Rf ~/Library/Preferences/AndroidStudio* rm ~/Library/Preferences/com.google.android.studio.plist rm -Rf ~/Library/Application\ Support/A

react-native —— 在Mac上搭建React Native Android开发环境

需要:JDK,Android SDK,Node.js 1.安装JDK 去Java官网下载列表选择Mac OS X x64版 2.安装Android SDK 虽然现在谷歌推荐使用Android Studio,但是我还是选择了单独安装Android SDK. 这是一个比较全的目录,上面的链接是官方的,有wall,用下面的基本都是网盘资源,速度还可以,记得修改Android SDK在线更新镜像服务器. PS:在Android SDK Manager里要装API 23的 安装完成后,一定要设置环境变量:

React Native:使用 JavaScript 构建原生应用 详细剖析

数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生的 iOS 应用——就在今天,Beta 版的仓库释出了! 基于 PhoneGap 使用 JavaScript 和 HTML5 开发 iOS 应用已经有好几年了,那 React Native 有什么牛的? React Native 真的很牛,让大家兴奋异常的主要原因有两点: 可以基于 React Native使用 JavaScript 编写应用逻辑,UI 则可以保持全是

React Native:使用 JavaScript 构建原生应用

[转载] 本篇为联合翻译,译者:寸志,范洪春,kmokidd,姜天意 数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生的 iOS 应用--就在今天,Beta 版的仓库释出了! 基于 PhoneGap 使用 JavaScript 和 HTML5 开发 iOS 应用已经有好几年了,那 React Native 有什么牛的? React Native 真的很牛,让大家兴奋异常的主要原因有两点: 可以基于 React Na

深入浅出 React Native:使用 JavaScript 构建原生应用

本篇为联合翻译,译者:寸志,范洪春,kmokidd,姜天意 数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生的 iOS 应用--就在今天,Beta 版的仓库释出了! 基于 PhoneGap 使用 JavaScript 和 HTML5 开发 iOS 应用已经有好几年了,那 React Native 有什么牛的? React Native 真的很牛,让大家兴奋异常的主要原因有两点: 可以基于 React Native使

React Native的极简手册

安装入门可以参考:React Native官方文档(http://reactnative.cn/docs/0.31/tutorial.html#content). NodeJS知识储备:参考<NodeJS入门>(https://leanpub.com/nodebeginner-chinese).(尊重知识,请购买原版). 书籍:<React Native入门与实战> 代码示例:30天学习React Native教程(https://github.com/fangwei716/30-

【React Native开发】React Native For Android环境配置以及第一个实例

转载请标明出处: http://blog.csdn.net/developer_jiangqq/article/details/50456967 本文出自:[江清清的博客] (一)前言 FaceBook早期开源发布了React Native For IOS,终于在2015年9月15日也发布了ReactNative for Android,虽然Android版本的项目发布比较迟,但是也没有阻挡了广大开发者的热情.可以这样讲在2015年移动平台市场上有两个方向技术研究比较火,第一种为阿里,百度,腾讯

我的 React Native 技能树点亮计划 の React Native 开发 IDE 选型和配置

@author ASCE1885的 Github 简书 微博 CSDN 知乎 本文首发于 InfoQ 移动技术公众号:移动开发前线 由于潜在的商业目的,未经许可不开放全文转载许可,谢谢! React Native 发布一年多了,有不少公司已经在线上产品中或小范围试水,或大范围应用,很多公司或开发者都在为 React Native 的生态系统作出自己的贡献.React Native 的开发基本上是 Javascript + 系统原生开发语言(Java,Objective-C,Swift),原生语言