首頁 >web前端 >js教程 >適用於您日常工作流程的 ESEST 提示、技巧、最佳實踐和程式碼片段範例

適用於您日常工作流程的 ESEST 提示、技巧、最佳實踐和程式碼片段範例

Barbara Streisand
Barbara Streisand原創
2024-09-22 06:22:02308瀏覽

ESESTips, Tricks, Best Practices, and Code Snippet Examples for Your Day-to-Day Workflow

ES6 (ECMAScript 2015) 對 JavaScript 進行了重大改革,引入了許多新功能,可以簡化您的編碼並提高專案的整體品質。

在這篇文章中,我們將介紹一些ES2015 提示、技巧、最佳實踐,並提供程式碼片段範例來增強您的日常工作流程。

1. 宣告變數:let 和 const 與 var

在 ES5 中,變數是使用 var 宣告的,它具有函數作用域的行為,導致提升和作用域可見性問題。 ES6 引入了具有區塊作用域的 let 和 const,提供了對變數宣告的更好控制。

常量:

定義常數變數:

const variableName = "value"

常數變數不能更改、重新分配或重新定義:

const variableName = "other value"  
   //-->SyntaxError: Identifier 'variableName' has already been declared
variableName = "other value" 
   //-->TypeError: Assignment to constant variable.

您可以更改、為常數數組添加值,但不能重新分配或重新定義它:

const arrayName = [1,2,3,4]
arrayName.push(5) 
   // Output -->[1,2,3,4,5]
const arrayName = [9,8,7,6] 
   //-->SyntaxError: Identifier 'arrayName' has already been declared

您可以更改常數物件、為其添加值,但不能重新指派或重新定義它:

const person = {name:"Developer",email:"developer@developer.com",city:"New Delhi"}
person.name ="Developer 2" //change a property 
person.location = "Gurugram" //add a new property
person = {name:"Dilip",email:"dilip@abc.com",city:"Delhi"} //reassign it 
   //-->SyntaxError: Identifier 'arrayName' has already been declared

常數變數存在於區塊作用域:

var x = 1
{ //this is a block scope
    const x = 2
}
console.log(x) 
    //Output -->1

讓:

定義一個let變數:

let variableName = "value"

讓變數存在於區塊作用域:

var x = 1
{ //this is a block scope
    let x = 2
}
console.log(x) //Output -->1

let 變數不能重新定義,但可以重新賦值:

let variableName = "other value"  
    //-->SyntaxError
variableName = "other value"

提升 - var 與 let:

由 var 定義的變數被提升到頂部

console.log(sayHello)
    //Output -->undefined
//variable sayHello is hoisted at the top before it was defined by var
//This means that variable is there but with value of undefined
var sayHello = "Hello World" 
console.log(sayHello)
    //Output -->"Hello World"

let 定義的變數不會被提升到頂部

console.log(sayHello)
     //-->ReferenceError: Cannot access 'sayHello' before initialization/defined
let sayHello = "Hello World"
console.log(sayHello)
    //Output -->"Hello World"

for循環中應該使用let而不是var,因為var定義的變數會洩漏到for循環之外,並且只有在有setTimeout函數時才會引用i的最終結果:

與 var

for (var i = 0; i < 3; i++) {
     console.log(i);
     setTimeout(function(){
          console.log("The number is " + i);
     }, 1000);
};
//after 1 sec
    //-->The number is 2  (x3)   
//setTimeout reference i after when the for loop ends
console.log(i)
    //--> 2
//i is leaked outside the for loop

與let

for (let i = 0; i < 3; i++) {
     setTimeout(function(){
          console.log("The number is " + i);
     }, 1000);
}
//after 1 sec
    //-->The number is 0
    //-->The number is 1
    //-->The number is 2

最佳實務:對於不會改變的變數使用const,對於需要在特定區塊內改變的變數使用let。避免使用 var 以防止與作用域相關的問題。


2. 箭頭功能

箭頭函數是定義函數的新方法,程式碼更簡潔,常用於回呼函數。
箭頭函數允許我們編寫更短的函數語法。
定義一個有 return 的箭頭函數:

let myFunction = (a, b) => {
  sum = a * b;
  return sum;
}

定義一個不帶回傳值的箭頭函數:

let myFunction = (a, b) => a * b;

如果沒有參數,可以直接使用括號:

let myFunction = () => ("Hello world");  

ES6 之前的方式相同

function functionName(param1,param2){
     return param1+param2;
}

回呼函數常用箭頭函數:

let myArr = [1,2,3]
let doubleThenFilter = arr => arr.map((value) => (value * 2) )
                                  .filter((value) => (value % 3 === 0));
doubleThenFilter(myArr)

ES6 之前的方式相同

function doubleThenFilter(arr){
    return arr.map(function(value){
        return value *2;
    }).filter(function(value){
        return value % 3 === 0;
    })
};

最佳實踐:使用箭頭函數作為匿名函數和回調,以使程式碼更短並避免問題。


3. 模板文字與字串連接

在 ES5 中,字串連接需要使用 +,這使得管理複雜或多行字串變得困難。 ES6 引入了模板文字,允許使用反引號嵌入表達式和多行字串。
模板文字使用反引號 (` `) 而不是引號 ("") 來定義字串。
模板字串是您處理字串的快速方法。
您可以引用變數:

let first = "Dilip";
let last = "Mishra";

console.log(`Hello, ${first} ${last}`);
//Output --> "Hello, Dilip Mishra"

ES6 之前的方式相同:

let first = "Dilip";
let last = "Mishra";
var greeting = 'Hello, ' + name + '!';

console.log('Hello, ' + first + ' ' +last);  
//Output --> "Hello, Dilip Mishra"

範本文字允許在字串中使用單引號和雙引號:

範本文字允許多行字串。
你可以只換行,使用 tab 而不使用 n t :

let text =
'The quick
brown fox
jumps over
the lazy dog';
  //Output -->  "The quick
brown fox
jumps over
the lazy dog"

模板文字允許在字串中表達:

let price = 10;
let VAT = 0.25;

let total = 'Total: ${(price * (1 + VAT)).toFixed(2)}';
  //Output -->  "Total: 12.50"

最佳實踐:在處理涉及動態內容或跨多行的字串時,使用範本文字以獲得更好的可讀性。


4. 解構賦值與傳統訪問

解構可讓您將陣列和物件中的值解壓縮到變數中,從而減少重複程式碼並增強可讀性。

定義與屬性同名的變數並賦值:

const person = { name: 'John', age: 30 };
const { name, age } = person;

console.log(name, age);  //Output --> John 30

定義屬性並為具有不同名稱的變數賦值:

const person = { name: 'John', age: 30 };
const { name:username, age:userage } = person;

console.log(username, userage);  //Output --> John 30

ES6 之前的方式相同

var person = { name: 'John', age: 30 };
var name = person.name;
var age = person.age;

console.log(name, age);  //Output --> John 30

陣列解構將陣列中的值指派給不同的變數:

var arr = [1,2,3];
var [a,b,c] = arr;
console.log(a); //-->1
console.log(b); //-->2
console.log(c); //-->3

最佳實踐:使用解構可以更清晰、更直觀地存取陣列和物件的屬性。


5. Default Parameters vs Fallback Logic

ES5 required manual fallback logic to handle missing function arguments, while ES6 introduced default parameters to define fallback values directly in the function signature.

ES5:

function myFunction(x, y) {
  var y = y || 10;
  return x + y;
}
myFunction(5); // will return 15

ES6:

function myFunction(x, y = 10) {
  // y is 10 if not passed or undefined
  return x + y;
}
myFunction(5); //Output --> will return 15

Best Practice: Use default parameters to handle optional function arguments cleanly.


6. Spread Operator vs concat() or apply()

The spread operator (...) allows for simpler merging of arrays and objects and is much more intuitive than using concat() or apply().

ES5:

var arr1 = [1, 2];
var arr2 = [3, 4];
var combined = arr1.concat(arr2);

console.log(combined);  // [1, 2, 3, 4]

ES6:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];

console.log(combined);  // [1, 2, 3, 4]

A spread operator would break down an array into values so that they can be easily used:

let nums = [4,5,6];
let nums2 = [1,2,3,...nums,7,8];
console.log(nums2);
    //--> [1,2,3,4,5,6,7,8]

Spread operator is commonly used when a function doesn’t accept an array as a parameter:

function sumValues(a,b,c){
     console.log(arguments);  //print out an array of the arguments of the function
return a+b+c;
}
let nums = [2,3,4];
sumValues(...nums); //values 2,3,4 of nums array has been passed to a,b,c parameters
    //-->[2,3,4]
    //-->9
sumValues(5,5,...nums); //value 2 of nums array has been passed to c parameter
    //-->[5,5,2,3,4]
    //-->12

Another example

let nums = [1,2,3,4];
Math.min(nums);
    //--> NaN
Math.min(...nums);
    //-->1

Best Practice: Use the spread operator for array concatenation, cloning objects, and passing variable arguments into functions.


7. Promises vs Callbacks

In ES5, asynchronous operations were typically handled with callbacks, leading to complex "callback hell" situations. ES6 introduced Promises, which simplify async code.

ES5:

function fetchData(callback) {
  setTimeout(function() {
    callback('Data loaded');
  }, 1000);
}

fetchData(function(data) {
  console.log(data);  // Data loaded
});

ES6:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('Data loaded'), 1000);
  });
}

fetchData().then(data => console.log(data));  // Data loaded

Best Practice: Use Promises (and async/await in modern code) for asynchronous code, as they provide a cleaner and more manageable approach.


8. Classes vs Constructor Functions

ES6 introduced class syntax as syntactic sugar over constructor functions for object-oriented programming. This provides a cleaner, more intuitive way to define and inherit from classes.

ES5:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  return 'Hello, I am ' + this.name;
};

var john = new Person('John', 30);
console.log(john.greet());  // Hello, I am John

ES6:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, I am ${this.name}`;
  }
}

const john = new Person('John', 30);
console.log(john.greet());  // Hello, I am John

Best Practice: Use classes to handle object creation and inheritance when working with OOP patterns in JavaScript.


9. Modules (import/export) vs IIFE or Global Functions

Prior to ES6, JavaScript did not have native module support. Developers had to use Immediately Invoked Function Expressions (IIFE) or rely on global variables. ES6 introduced import and export, allowing modular code organization.

ES5 (IIFE):

(function() {
  function add(x, y) {
    return x + y;
  }
  window.add = add;
})();

console.log(add(2, 3));  // 5

ES6 (Modules):

// math.js
export function add(x, y) {
  return x + y;
}

// main.js
import { add } from './math.js';
console.log(add(2, 3));  // 5

Best Practice: Use ES6 modules for better code organization, reusability, and easier dependency management.


10. Async/await

Async

The ansync keyword that placed before a function makes that the function behave like a Promise:

async function myFunc(){
    return "this is a promise";
}
myFunc().then((val)=>{console.log(val)});
    //-->"this is a promise"

In an async function, the return keyword will act like the resolve keyword in a Promise, the throw keyword will act like the reject keyword in a Promise

async function doHomework(){
    let isDone = false;
    if (isDone){
        return("is done");
    }else{
        throw "is not done";
    }
}
doHomework().then(function(homeworkResult){
    console.log("The homework " + homeworkResult);
}).catch(function(homeworkResult){
    console.log("The homework " + homeworkResult);
})
    //"The homework is not done"

Await

The await keyword is ONLY used in the async function. The await keyword makes your code wait until the Promise inside the function has been fulfilled/rejected:

async function myFunc(){
    let myPromise = new Promise((resolve,reject)=>{
        setTimeout(()=>{resolve("done!")},1000)
    });
    let result = await myPromise; //wait for this promise before continuing
    return result;
}
myFunc().then((result)=>{console.log(result)})


Final Thoughts

ES6 has drastically improved the way JavaScript is written and maintained. Adopting these tips and practices in your daily workflow will not only make your code cleaner but also more maintainable and scalable. Whether you're switching from ES5 or enhancing your ES6 skills, these tricks will help you stay productive.

Contributions Welcome! If you have additional tips, tricks, or use cases from your experience, feel free to share them in the comments.

Happy coding!

以上是適用於您日常工作流程的 ESEST 提示、技巧、最佳實踐和程式碼片段範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn