重点(Top highlight)
Every JavaScript developer should understand the basic concepts of this complex language.
每个JavaScript开发人员都应该了解这种复杂语言的基本概念。
The below concepts are not all, but these are the common foundational ones you need to know to take a step forward.
以下概念并非全部,但它们是您迈出一步需要了解的常见基础知识。
Let’s dive right in.
让我们潜入。
1. IIFE (1. IIFE)
It stands for Immediately Invoked Function Expression. It’s the function that is called immediately after it’s created.
它代表立即调用函数表达式。 创建后立即调用该函数。
How can you define an IIFE? Look at the example below:
您如何定义IIFE? 看下面的例子:
(() => console.log(‘Hello world’))();
As the code is executed, the console will log Hello world immediately.
执行代码后,控制台将立即记录Hello world 。
The reason to use IIFE is to protect variables accessibility. The variables defined in IIFE can not be accessed from the outside. That’s the way to write maintainable code and prevent your source from becoming a mess.
使用IIFE的原因是为了保护变量的可访问性。 IIFE中定义的变量不能从外部访问。 这就是编写可维护代码并防止源代码混乱的方式。
2. MVC结构 (2. MVC Structure)
Not only in JavaScript, but this structure is used in almost programming languages. Far from the name MVC, it’s a popular concept to organize your code into different layers like data, view, and logic and treat them separately.
不仅在JavaScript中,而且几乎在所有编程语言中都使用此结构。 它远非MVC的名称,它是一个流行的概念,它可以将您的代码组织到不同的层(如数据,视图和逻辑)中,并分别进行处理。
As a project going big, you need a structure to scale it up without putting your head to the wall. MVC is one of the best to follow in the first place for the long term plan. At some points in the future when adding new features or investigate bugs, you will thank yourself for spending time implementing MVC in the past.
随着项目的进行,您需要一种结构来扩大规模,而又不会陷入困境。 对于长期计划而言,MVC是首屈一指的最佳方式之一。 在将来的某些时候,添加新功能或调查错误时,您将感谢您过去花费大量时间实施MVC。
3.关闭 (3. Closure)
We use this concept when talking about an inner function that always has access to the variables and parameters of its outer function, even after the outer function has returned.
在谈论内部函数时,即使在外部函数返回后,也始终可以访问其外部函数的变量和参数,我们使用此概念。
Closure allows you to give accessibility to data inside a function without directly modifying them. This way, you can protect your code while giving others the ability to extend it. Especially when you public a library.
闭包使您可以直接访问函数中的数据,而无需直接修改它们。 这样,您可以在保护代码的同时让其他人对其进行扩展。 尤其是当您公开图书馆时。
const sayHelloTo = name => {
let message = ‘Hello ‘ + name;
return () => console.log(message);
}const sayHelloToAmy = sayHelloTo(‘Amy’);
sayHelloToAmy(); // Hello Amy
4.异步/等待 (4. Async/await)
Async/await allows you to work with asynchronous processing. You usually fall into asynchronous tasks when dealing with calling API. The data need to be fully fetched before showing up on the view.
异步/等待允许您使用异步处理。 处理调用API时,您通常会陷入异步任务。 在显示在视图上之前,需要完全获取数据。
What makes me satisfied with using async/await is I can get rid of callbacks hell. If you’re anything like me, you don’t like nested code. It makes your code ugly and less maintainable.
使我对使用异步/等待感到满意的是,我可以摆脱回调地狱。 如果您像我一样,就不喜欢嵌套代码。 它使您的代码难看且难以维护。
See the example below for async/await usage:
请参阅下面的示例以了解异步/等待的用法:
const displayData = async () => {
const data = await fetch(‘https://api.github.com/repositories');
const jsonData = await data.json();
console.log(jsonData);
};displayData();
5.范围 (5. Scope)
There are two types of scope in JavaScript. The local scope and the global one. You can imagine a variable scope is a cow tied to a post by a rope. It can only move in a limited area, depending on the length of the rope.
JavaScript有两种作用域。 本地范围和全球范围。 您可以想象可变范围是用绳子绑在柱子上的母牛。 它只能在有限的区域内移动,具体取决于绳索的长度。
With that metaphor, the local variable is like a cow tied by a short rope and the global one is like a cow with no rope at all.
用这种比喻,局部变量就像一头被短绳绑住的母牛,而全局变量就像一头根本没有绳子的母牛。
For example:
例如:
// Global scope
const globalCow = ‘global cow’;const showCow = () => {
const localCow = ‘local cow’;
return globalCow;
};const clonedCow = globalCow;const mixedCow = globalCow + localCow; // error: Uncaught ReferenceError: localCow is not defined
As you can see, the variable globalCow can be used anywhere even in the local context of the function showCow. But you can’t use the variable localCow outside the function showCow since it’s defined locally.
正如你所看到的,变量globalCow可以在任何地方,甚至在功能showCow的局部环境中使用。 但因为它是本地定义的,你不能使用变量localCow功能showCow之外。
6.值与引用类型 (6. Value vs Reference Types)
When you assign values to variables, it’s not that simple to just assign the values. You need to understand whether it’s the actual values or references, otherwise, you probably change the values unintentionally.
在为变量分配值时,仅分配值并不是那么简单。 您需要了解它是实际值还是引用,否则,您可能无意中更改了值。
The story is easy when you assign primitive types such as string, number, or boolean. They’re actual values.
当您分配原始类型(例如字符串,数字或布尔值)时,故事很容易。 它们是实际值。
A little bit more complex if you assign objects, arrays, or functions. This time, the variable won’t hold the actual value but the reference to the actual value in the memory.
如果分配对象,数组或函数,则稍微复杂一点。 这次,变量将不保存实际值,而是保存内存中对实际值的引用。
Example:
例:
let num1 = 1;
let num2 = num1;// Changing num2’s value does not change num1’s value
num2 = 4;
console.log(num1); // 1
console.log(num2); // 4
let arr1 = [‘Amy’, ‘John’];
let arr2 = arr1;// Changing elements’ value in arr2 leads to changing elements’ value in arr1
arr2[0] = ‘Jane’;
console.log(arr1); // [“Jane”, “John”]
console.log(arr2); // [“Jane”, “John”]
7.回调 (7. Callback)
In JavaScript, a callback function is a function that is executed after another function is called. You can pass a callback function as a parameter to other functions.
在JavaScript中,回调函数是在调用另一个函数之后执行的函数。 您可以将回调函数作为参数传递给其他函数。
So why do we use callback? Normally, the code we write runs sequentially from top to bottom. In some cases, however, there’re tasks need to be done before executing others. This is when callback comes in handy.
那为什么要使用回调呢? 通常,我们编写的代码从上到下依次运行。 但是,在某些情况下,在执行其他任务之前需要完成一些任务。 这是回调很方便的时候。
const fetchUsers = callback => {
setTimeout(() => {
let response = ‘[{name: “Amy”}, {name: “John”}]’;
callback(response);
}, 500);
};const showUsers = users => console.log(users);
fetchUsers(showUsers);
In the example above, we call fetchUsers function and pass showUsers callback function as a parameter. When all the data is fully loaded, showUsers will display it on the screen.
在上面的示例中,我们调用fetchUsers函数,并将showUsers回调函数作为参数传递。 当所有数据完全加载后, showUsers会将其显示在屏幕上。
8.原型 (8. Prototype)
Whenever we create a function or object in JavaScript, a prototype property will be added inside them. A prototype is an object associated with functions and objects by default, in which we can attach additional properties that can be inherited by other objects.
每当我们在JavaScript中创建函数或对象时,都会在其中添加原型属性。 原型是默认情况下与功能和对象相关联的对象,在其中我们可以附加其他对象可以继承的其他属性。
Example:
例:
function Person() {
this.name = ‘Amy’;
this.age = 28;
}Person.prototype.job = ‘Programmer’;
Person.prototype.showName = function() {
console.log(‘My name is ‘ + this.name);
}let person = new Person();
person.showName(); // My name is Amy
9.班级 (9. Class)
Prior to ES6, there are no classes in JavaScript. You can only approach the like-class concept in a functional way.
在ES6之前,JavaScript中没有类。 您只能以实用的方式处理类似类的概念。
function Book(title) {
this.title = title;
}Book.prototype.showTitle = function() {
console.log(this.title);
};let book = new Book(‘JavaScript’);
book.showTitle(); // JavaScript
In ES6, you can create an actual class like any class-based language background:
在ES6中,您可以像任何基于类的语言背景一样创建实际的类:
class Book {
constructor(title) {
this.title = title;
} showBook() {
console.log(this.title);
}
}let book = new Book(‘ES6’);
book.showBook();
It’s convenient because it unifies several way of creating classes into a single one.
这很方便,因为它将创建类的几种方法统一为一个。
10.破坏 (10. Destructing)
It’s a clean way to extract properties from objects.
Basic usage:
基本用法:
const person = {
name: ‘Amy’,
age: 28
};let { name, age } = person;
console.log(name); // Amy
console.log(age); // 28
You can keep variables the same as properties name like above or define the new ones:
您可以将变量与上面的属性名称相同,也可以定义新的变量:
let { name: newName, age: newAge } = person;console.log(newName); // Amy
console.log(newAge); // 28
11.点差算子 (11. Spread Operator)
This one will give you access to the insides of an iterable object. Simply talk, it’s a quick and concise way for adding items to arrays, combining objects, or pull the individual items out of an array and then pass them to a function.
这将使您能够访问可迭代对象的内部。 简单地说,这是将项目添加到数组,组合对象或将单个项目从数组中拉出然后传递给函数的一种快速简洁的方法。
// Combining Arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = […arr1, …arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]// Combining Objects
let obj1 = {
name: ‘Amy’,
age: 28
};let obj2 = {
job: ‘programmer’
};let obj3 = { …obj1, …obj2 };console.log(obj3); // {name: “Amy”, age: 28, job: “programmer”}// Spreading out an array and pass it to a function
const sum = (…arr) => {
const length = arr.length;
let sum = 0; for (let i = 0; i < length; i++) {
sum += arr[i];
} return sum;
};let arr = [3, 5, 3, 2, 1];
console.log(sum(…arr)); // 14
console.log(sum(3, 5, 4, 1)); // 13
结论 (Conclusion)
Do you fully understand all of the concepts above? If not, it’s time to examine all of them and be ready to take your skills to the next level.
您是否完全理解上述所有概念? 如果没有,那么该是检查所有这些内容并准备将您的技能提升到更高水平的时候了。
Do I miss anything? Please leave the comment to let me know.
我想念什么吗? 请留下评论让我知道。
进一步阅读 (Further reading)
普通英语JavaScript(JavaScript In Plain English)
Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!
喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容!