Android:ReactNative語法基礎(上)
ES6特性
- 類
- 模組化
- 箭頭函式
- 函式引數預設值
- 模板字串
- 解構賦值
- 延展操作符
- 物件屬性簡寫
- Promise
- Let與Const
1、類
引入類的概念,讓其具有面向物件的開發
class Person { constructor(name,age) { this.name = name; this.age = age; } }
2、模組化
模組之間的相互呼叫關係是通過export來規定模組對外暴露的介面,通過import來引用其它模組提供的介面
export var name = 'Rainbow';//匯出變數 export const sqrt = Math.sqrt;//匯出常量 var name = 'Rainbow';//匯出多個變數 var age = '24'; export {name, age}; export function myModule(someArg) {//匯出函式 return someArg; } export default class MyComponent extends Componet{//匯出元件 render(){ <Text>自定義元件</Text> } }
定義好模組的輸出以後就可以在另外一個模組通過import引用
import {myModule} from 'myModule';//匯入函式 import {name,age} from 'test';//匯入變數 import MyComponent from 'MyComponent' //匯入元件
3、箭頭函式
箭頭函式與包圍它的程式碼共享同一個this,能幫你很好的解決this的指向問題
()=>{ alert("foo"); }
錯誤示範
class PauseMenu extends React.Component{ componentWillMount(){ AppStateIOS.addEventListener('change', this.onAppPaused.bind(this)); } componentWillUnmount(){ AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this)); } onAppPaused(event){ } }
正確示範
class PauseMenu extends React.Component{ componentWillMount(){ AppStateIOS.addEventListener('change', this.onAppPaused); } componentWillUnmount(){ AppStateIOS.removeEventListener('change', this.onAppPaused); } onAppPaused = (event) => { } }
4、函式引數預設值
function foo(height = 50, color = 'red'){}
5、模板字串
var name = `Your name is ${firstname} ${lastname}`
6、解構賦值
從陣列中獲取值
[a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7
交換兩個變數的值
var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1
獲取物件中的值
const student = { name:'Ming', age:'18', city:'Shanghai' }; const {name,age,city} = student; console.log(name); // "Ming" console.log(age);// "18" console.log(city); // "Shanghai"
7、延展操作符
延展操作符...,可以對陣列、物件、string進行展開操作
myFunction(...iterableObj);//對函式展開 [...iterableObj, '4', ...'hello', 6];//對陣列展開 let objClone = { ...obj };//對物件展開
對陣列展開
var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; var arr3 = [...arr1, ...arr2]; // 將 arr2 中所有元素附加到 arr1 後面並返回
對物件展開
var params = { name: '123', title: '456', type: 'aaa' } var { type, ...other } = params; <CustomComponent type='normal' number={2} {...other} /> //等同於 <CustomComponent type='normal' number={2} name='123' title='456' />
8、物件屬性簡寫
簡寫前
const name='Ming',age='18',city='Shanghai'; const student = { name:name, age:age, city:city }; console.log(student);
簡寫後
const name='Ming',age='18',city='Shanghai'; const student = { name, age, city }; console.log(student);
9、Promise
Promise是非同步程式設計的一種解決方案,在不使用Promise的時候需要巢狀多層程式碼 setTimeout(function() { console.log('Hello'); // 1秒後輸出"Hello" setTimeout(function() { console.log('Hi'); // 2秒後輸出"Hi" }, 1000); }, 1000);
使用Promise後,只需要通過then操作符進行操作
var waitSecond = new Promise(function(resolve, reject) { setTimeout(resolve, 1000); }); waitSecond .then(function() { console.log("Hello"); // 1秒後輸出"Hello" return waitSecond; }) .then(function() { console.log("Hi"); // 2秒後輸出"Hi" });
10、Let與Const
const與let都是塊級作用域 { var a = 10;// 全域性作用域 } console.log(a); // 輸出10 { let a = 10;// const或let,塊級作用域 } console.log(a); //-1 or Error“ReferenceError: a is not defined”
ES7特性
- includes()
- 指數操作符
1、includes()
includes()函式用來判斷一個數組是否包含一個指定的值
arr.includes(x) //等同於 arr.indexOf(x) >= 0
2、指數操作符
引入了指數運算子, 具有與Math.pow(..) 等效的計算結果
console.log(Math.pow(2, 10)); // 輸出1024 console.log(2**10);// 輸出1024
ES8特性
- async/await
- Object.values()
- Object.entries()
- String padding
- 函式引數列表結尾允許逗號
- Object.getOwnPropertyDescriptors()
1、async/await
async/await是非同步函式,結合Promise,在使用上使整個程式碼看起來很簡潔
//登陸使用者 login(userName) { return new Promise((resolve, reject) => { setTimeout(() => { resolve('1001'); }, 600); }); } //獲取使用者資料 getData(userId) { return new Promise((resolve, reject) => { setTimeout(() => { if (userId === '1001') { resolve('Success'); } else { reject('Fail'); } }, 600); }); } // 不使用async/await doLogin(userName) { this.login(userName) .then(this.getData) .then(result => { console.log(result) }) } // 使用async/await async doLogin(userName) { const userId=await this.login(userName); const result=await this.getData(userId); } doLogin('Hensen').then(console.log); //通過then獲取非同步函式的返回值
async/await支援併發操作,我們通過Promise.all 來實現await的併發呼叫
async function charCountAdd(data1, data2) { const [d1,d2]=await Promise.all([charCount(data1),charCount(data2)]); return d1+d2; } charCountAdd('Hello','Hi') .then(console.log) .catch(console.log); //捕捉整個async/await函式的錯誤 function charCount(data) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(data.length); }, 1000); }); }
2、Object.values()
遍歷物件的所有值
const obj = {a: 1, b: 2, c: 3}; const vals=Object.keys(obj).map(key=>obj[key]); console.log(vals);//[1, 2, 3] const values=Object.values(obj1); console.log(values);//[1, 2, 3]
3、Object.entries()
遍歷物件的所有key和value
Object.keys(obj).forEach(key=>{ console.log('key:'+key+' value:'+obj[key]); }) for(let [key,value] of Object.entries(obj1)){ console.log(`key: ${key} value:${value}`) }
4、String padding
PadStart和PadEnd 函式可向左、右填充字串(如空格),如果目標長度太短則不填充,如果目標長度有多餘的空位,則填補引數padString 的值
// String.prototype.padStart(targetLength [, padString]) 'hello'.padStart(10); // 'hello' 'hello'.padStart(10, '0'); // '00000hello' 'hello'.padStart(); // 'hello' 'hello'.padStart(6, '123'); // '1hello' 'hello'.padStart(3); // 'hello' 'hello'.padStart(3, '123'); // 'hello'; // String.prototype.padEnd(targetLength [, padString]) 'hello'.padEnd(10); // 'hello' 'hello'.padEnd(10, '0'); // 'hello00000' 'hello'.padEnd(); // 'hello' 'hello'.padEnd(6, '123'); // 'hello1' 'hello'.padEnd(3); // 'hello' 'hello'.padEnd(3, '123'); // 'hello';
5、函式引數列表結尾允許逗號
var f = function(a,b,c,d,) {}
6、Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors()獲取一個物件的所有自身屬性的描述符
const obj2 = { name: 'Jine', get age() { return '18' } }; Object.getOwnPropertyDescriptors(obj2)