在 React 开发过程中必备的一些 JS 语法整理, 摘自 “Learning React” 一书.
关于 JS 编译
由于需要使用最新的 JS 语法且又想让尽可能广的浏览器得到支持, 因此需要使用编译工具, 比较知名的是 babel.
而编译过程一般都会被 build tool 自动化, 比如 webpack 或 parcel.
解构
-
从对象解构属性:
jsconst sandwich = { bread: "dutch crunch", meat: "tuna", cheese: "swiss", toppings: ["lettuce", "tomato", "mustard"] }; const { bread, meat } = sandwich; console.log(bread, meat); // dutch crunch tuna -
解构出的变量和原对象无关, 因此可以对解构后的变量进行修改:
js// ... let { bread, meat } = sandwich; bread = "garlic"; meat = "turkey"; console.log(bread); // garlic console.log(meat); // turkey console.log(sandwich.bread, sandwich.meat); // dutch crunch tuna -
可以在函数参数上使用解构的语法, 这样当传入对象时, 可以直接从对象中解构对应的属性:
jsconst lordify = ({ firstname }) => { console.log(`${firstname} of Canterbury`); }; const regularPerson = { firstname: "Bill", lastname: "Wilson" }; lordify(regularPerson); // Bill of Canterbury -
甚至可以对对象中的对象进行解构, 比如对象属性又是一个对象的情况:
jsconst lordify = ({ spouse: { firstname } }) => { console.log(`${firstname} of Canterbury`); }; -
数组的解构:
js// 获取第一个元素, Horse const [firstAnimal] = ["Horse", "Mouse", "Cat"]; // 使用逗号获取最后一个元素: Cat const [, , thirdAnimal] = ["Horse", "Mouse", "Cat"];
展开操作符: ...
-
使用
...将两个数组合成一个:jsconst peaks = ["Tallac", "Ralston", "Rose"]; const canyons = ["Ward", "Blackwood"]; const tahoe = [...peaks, ...canyons]; -
使用
...创建一个数组的拷贝:js// 拷贝数组后对数组进行反向, 从而获取之前数组中的第一个元素 const peaks = ["Tallac", "Ralston", "Rose"]; const [last] = [...peaks].reverse(); -
使用
...获取数组中的剩余元素:jsconst lakes = ["Donner", "Marlette", "Fallen Leaf", "Cascade"]; const [first, ...others] = lakes; console.log(others.join(", ")); // Marlette, Fallen Leaf, Cascade -
使用
...将函数参数组织为数组:jsfunction directions(...args) { let [start, ...remaining] = args; let [finish, ...stops] = remaining.reverse(); // ... } -
使用
...将一个对象中的所有属性展开到另外一个对象中:jsconst morning = { breakfast: "oatmeal", lunch: "peanut butter and jelly" }; const dinner = "mac and cheese"; // 将 morning 的内容, 以及 dinner 都放到新对象中. const backpackingMeals = { ...morning, dinner };
JS 简单异步操作
-
使用
fetch进行网络请求:jsfetch("https://api.randomuser.me/?nat=US&results=1").then(res => console.log(res.json()) ); -
使用 Async/Await:
jsconst getFakePerson = async () => { let res = await fetch("https://api.randomuser.me/?nat=US& results=1"); let { results } = res.json(); console.log(results); }; getFakePerson(); -
构造 Promise:
jsconst getPeople = count => new Promise((resolves, rejects) => { const api = `https://api.randomuser.me/?nat=US&results=${count}`; const request = new XMLHttpRequest(); request.open("GET", api); request.onload = () => request.status === 200 ? resolves(JSON.parse(request.response).results) : reject(Error(request.statusText)); request.onerror = err => rejects(err); request.send(); }); // 使用时(当然也可以使用 async/await 语法) getPeople(5) .then(members => console.log(members)) .catch(error => console.error(`getPeople failed: ${error.message}`)));
JS 的 Class 语法
在 ES2015 之后, 引入了官方的 class 语法支持. 在此之前, “类” 的定义一般是这样进行的:
function Vacation(destination, length) { this.destination = destination; this.length = length; } Vacation.prototype.print = function() { console.log(this.destination + " | " + this.length + " days"); }; // 使用 new 关键字实例化对象. const maui = new Vacation("Maui", 7); maui.print(); // Maui | 7 days
class 只是一种 prototype 语法上的语法糖:
class Vacation { constructor(destination, length) { this.destination = destination; this.length = length; } print() { console.log(`${this.destination} will take ${this.length} days.`); } } // 使用时: const trip = new Vacation("Santiago, Chile", 7); trip.print(); // Chile will take 7 days.
继承的语法:
class Expedition extends Vacation { constructor(destination, length, gear) { super(destination, length); this.gear = gear; } print() { super.print(); console.log(`Bring your ${this.gear.join(" and your ")}`); } }
ES6 模块(Modules)
JS 模块的意思是单个的可重用代码集合, 通过模块解决名字冲突, 而 JS 的模块保持在单个文件中, 一个文件一个模块.
使用 export 导出模块中的变量, 通过 import 引入另外一个模块中的变量. 如果只想导出一个变量, 则可以使用 export default.
import 的时候:
// 使用对象解构的语法获得模块中 export 的变量 import { print, log } from "./text-helpers"; // 使用 export default 的变量可以直接导出到单个变量 import freel from "./mt-freel"; // 使用 as 语法重命名 import { print as p, log as l } from "./text-helpers"; // 使用 import * 导出全部变量 import * as fns from './text-helpers`
CommonJS
CommonJS 是另外一种模块风格, 在 Node 中使用的.
export 语法:
const print(message) => log(message, new Date()) const log(message, timestamp) => console.log(`${timestamp.toString()}: ${message}`} module.exports = {print, log}
import 语法:
const { log, print } = require("./txt-helpers");