+
+
Posts List
  1. 前言
  2. 学习计划
    1. 打基础
  3. 查漏补缺
    1. 函数
      1. 函数表达式
      2. 箭头函数
        1. Concise Body Arrow Functions
      3. 迭代器 iterators
    2. 对象 Object
    3. 类 class
    4. 模块 Modules
    5. Promise
    6. Async Await

JavaScript 回炉计划

前言

最早接触到JS,应该是中学下载安装游猴脚本的时候;之后在大一的选修课上也上过一堂JS的课;最近的一次就是参加小程序比赛时开发小程序的实战经历了。

对于我这种不爱看书,也不爱学习别人代码的人,实战的确是最能提升编程技能的方法。不过,弊端也很多,但凡问点概念上的问题,我就一问三不知了,即便是手撸代码,也一定是半屏IDE,半屏搜索引擎。

想着毕业找工作简历上不能都写些“了解”、“涉猎”、“接触”,便打算在暑假把JS回炉重造一下,让简历上好歹能有一项“熟练”。

学习计划

虽然要回炉JS,但这不代表我就愿意看书了。边看边码代码,电脑屏幕对我来说要友好太多。

打基础

到油管上看一看有关前端的视频,对要学习的东西大体有个框架。(起码不会出现先学JQuery再学JavaScript这种笑话)
What You Need to Know to be a Front End Developer in 2018

Codecademy是我在中学接触到的一个在线编程学习网站,用来学习基础概念很不错,虽然课程是收费的,但是新注册用户有 7 Days Free Trail,而我怎么可能缺邮箱呢😎。

打算两天时间在Codecademy上过一遍Introduction To JavaScript的教程,按照官网介绍,可以基本掌握编程基础和面向对象的基本概念。

之前学过C、Python,所以编程基础还是有的,不过,多学一遍总不会有错的。

然后打算看看两位峰哥(廖雪峰、阮一峰)的JS教程和MDN的文档:

查漏补缺

函数

函数表达式

除了函数声明外,另一种定义函数的方式就是函数表达式

参考:JavaScript函数表达式 - Rich.W - 博客园

箭头函数

引入箭头函数有两个方面的作用:更简短的函数并且不绑定this。

1
2
3
4
5
6
7
8
9
10
11
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet: () => {
console.log(this.dietType);
}
};

goat.diet(); // Prints undefined

Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object. In the code snippet above, the value of this is the global object, or an object that exists in the global scope, which doesn’t have a dietType property and therefore returns undefined.

Concise Body Arrow Functions

比如

1
2
3
const plantNeedsWater = (day) => {
return day === 'Wednesday' ? true : false;
};

可以简写为:

1
const plantNeedsWater = day => day === 'Wednesday' ? true : false;

迭代器 iterators

  • .forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined.
  • .map() executes the same code on every element in an array and returns a new array with the updated elements.
  • .filter() checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.
  • .findIndex() returns the index of the first element of an array which satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition.
  • .reduce() iterates through an array and takes the values of the elements and returns a single value.

All iterator methods takes a callback function that can be pre-defined, or a function expression, or an arrow function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const nums = [1, 50, 75, 200, 350, 525, 1000];

// Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));

// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);

// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, "C");

console.log(word)

// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);

// Choose a method that will return a boolean value
nums.every(num => num < 0);

对象 Object

One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered. Here’s an example of using _ to prepend a property.

1
2
3
const bankAccount = {
_amount: 1000
}

setter getter assign
Destructured Assignment

1
2
3
4
5
6
7
8
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
1
2
const { day } = vampire.preferences; 
console.log(day); // Prints 'stay inside'

类 class

JavaScript calls the constructor() method every time it creates a new instance of a class.

JavaScript will invoke the constructor() method every time we create a new instance of our Dog class.

We use the extends keyword to create a subclass.
The super keyword calls the constructor() of a parent class.
Static methods are called on the class, but not on instances of the class.

模块 Modules

Modules in JavaScript are reusable pieces of code that can be exported from one program and imported for use in another program.

module.exports exports the module for use in another program.
require() imports the module for use in the current program.
ES6 introduced a more flexible, easier syntax to export modules:

  • default exports use export default to export JavaScript objects, functions, and primitive data types.
  • named exports use the export keyword to export data in variables.
  • named exports can be aliased with the as keyword.
  • import is a keyword that imports any object, function, or data type.

Promise

Promises are objects that represent the eventual outcome of an asynchronous operation. A Promise object can be in one of three states:

  • Pending: The initial state— the operation has not completed yet.
  • Fulfilled: The operation has completed successfully and the promise now has a resolved value. For example, a request’s promise might resolve with a JSON object as its value.
  • Rejected: The operation has failed and the promise has a reason for the failure. This reason is usually an Error of some kind.

We refer to a promise as settled if it is no longer pending— it is either fulfilled or rejected. Let’s think of a dishwasher as having the states of a promise:

  • Pending: The dishwasher is running but has not completed the washing cycle.
  • Fulfilled: The dishwasher has completed the washing cycle and is full of clean dishes.
  • Rejected: The dishwasher encountered a problem (it didn’t receive soap!) and returns unclean dishes.
    If our dishwashing promise is fulfilled, we’ll be able to perform related tasks, such as unloading the clean dishes from the dishwasher. If it’s rejected, we can take alternate steps, such as running it again with soap or washing the dishes by hand.

All promises eventually settle, enabling us to write logic for what to do if the promise fulfills or if it rejects.

To create a new Promise object, we use the new keyword and the Promise constructor method:

1
2
const executorFunction = (resolve, reject) => { };
const myFirstPromise = new Promise(executorFunction);

The Promise constructor method takes a function parameter called the executor function which runs automatically when the constructor is called. The executor function generally starts an asynchronous operation and dictates how the promise should be settled.

1
2
3
4
5
6
7
8
function myExecutor(resolve,reject){
if (inventory.sunglasses > 0) {
resolve('Sunglasses order processed.')
}
else{
reject('That item is sold out.')
}
}

The executor function has two function parameters, usually referred to as the resolve() and reject() functions. The resolve() and reject() functions aren’t defined by the programmer. When the Promise constructor runs, JavaScript will pass its own resolve() and reject() functions into the executor function.

  • resolve is a function with one argument. Under the hood, if invoked, resolve() will change the promise’s status from pending to fulfilled, and the promise’s resolved value will be set to the argument passed into resolve().
  • reject is a function that takes a reason or error as an argument. Under the hood, if invoked, reject() will change the promise’s status from pending to rejected, and the promise’s rejection reason will be set to the argument passed into reject().

-

  • Promises are JavaScript objects that represent the eventual result of an asynchronous operation.
  • Promises can be in one of three states: pending, resolved, or rejected.
  • A promise is settled if it is either resolved or rejected.
  • We construct a promise by using the new keyword and passing an executor function to the Promise constructor method.
  • setTimeout() is a Node function which delays the execution of a callback function using the event-loop.
  • We use .then() with a success handler callback containing the logic for what should happen if a promise resolves.
  • We use .catch() with a failure handler callback containing the logic for what should happen if a promise rejects.
  • Promise composition enables us to write complex, asynchronous code that’s still readable. We do this by chaining multiple .then()‘s and .catch()‘s.
  • To use promise composition correctly, we have to remember to return promises constructed within a .then().
  • We should chain multiple promises rather than nesting them.
  • To take advantage of concurrency, we can use Promise.all().

Async Await

  • async...await is syntactic sugar built on native JavaScript promises and generators.

  • We declare an async function with the keyword async.

  • Inside an async function we use the await operator to pause execution of our function until an asynchronous action completes and the awaited promise is no longer pending .

  • await returns the resolved value of the awaited promise.

  • We can write multiple await statements to produce code that reads like synchronous code.

  • We use try...catch statements within our async functions for error handling.

  • We should still take advantage of concurrency by writing async functions that allow asynchronous actions to happen in concurrently whenever possible.

  • GET and POST requests can be created a variety of ways.

  • Use AJAX to asynchronously request data from APIs. fetch() and async/await are new functionalities developed in ES6 (promises) and ES8 respectively.

  • Promises are a new type of JavaScript object that represent data that will eventually be returned from a request.

  • fetch() is a web API that can be used to create requests. fetch() will return promises.

  • We can chain .then() methods to handle promises returned by fetch().

  • The .json() method converts a returned promise to a JSON object.

  • async is a keyword that is used to create functions that will return promises.

  • await is a keyword that is used to tell a program to continue moving through the message queue while a promise resolves.

  • await can only be used within functions declared with async.

本文作者: rhinoc

本文链接: https://www.rhinoc.top/js_1/

版权声明: 本博客所有文章除特别声明外,均采用BY-NC-SA 4.0国际许可协议,转载请注明。

打赏
Love U 3000
  • Through WeChat
  • Through Alipay