Ten advanced Javascript knowledge and usage

1. Higher order functions

A higher-order function is a function that takes one or more functions as arguments and/or returns a function. This technique can be used to combine functions to achieve function reuse.

// 高阶函数示例:将一个数组中的所有元素相加
function add(...args) {
  return args.reduce((a, b) => a + b, 0);
}
function addArrayElements(arr, fn) {
  return fn(...arr);
}
const arr = [1, 2, 3, 4, 5];
const sum = addArrayElements(arr, add);
console.log(sum); // 15
复制代码

2. Pure functions

A pure function is one that has no side effects (does not change external state) and whose output is determined only by its input. Pure functions allow for easier unit testing and debugging, and better support for functional programming concepts.

// 纯函数示例:将一个数组中的所有元素转换为字符串
function arrToString(arr) {
  return arr.map(String);
}
const arr = [1, 2, 3, 4, 5];
const strArr = arrToString(arr);
console.log(strArr); // ["1", "2", "3", "4", "5"]
复制代码

3. Closures

Closure means that a function can access variables outside its definition scope. This technique can be used to "privatize" variables, thereby avoiding the abuse of global variables.

// 闭包示例:使用闭包实现计数器
function makeCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3
复制代码

4. Currying

Currying is the technique of turning a function that takes multiple arguments into a sequence of functions that take one argument. This technique can be used to make functions more general.

// 柯里化示例:将一个接受多个参数的函数转换为一个接受一个参数的函数序列
function add(a) {
  return function(b) {
    return a + b;
  };
}
const add5 = add(5);
console.log(add5(10)); // 15
console.log(add5(20)); // 25
复制代码

5. Function composition

Function composition refers to the technique of combining multiple functions into a single function. This technique can be used to pass the output of multiple functions to the next function to realize the reuse of functions.

// 函数组合示例:将多个函数组合成一个函数
function add(a, b) {
  return a + b;
}
function multiply(a, b) {
  return a * b;
}
function compose(...fns) {
  return function(x, y) {
    return fns.reduce((acc, fn) => fn(acc, y), x);
  };
}
const addAndMultiply = compose(add, multiply);
console.log(addAndMultiply(2, 3)); // 15
复制代码

6. Function memoization

Function memoization refers to the use of cache to save the results of functions, thereby avoiding repeated calculations. This technique can be used to improve the performance of functions.

// 函数记忆化示例:使用缓存来保存函数的结果
function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}
function add(a, b) {
  console.log("Calculating sum...");
  return a + b;
}
const memoizedAdd = memoize(add);
console.log(memoizedAdd(2, 3)); // Calculating sum... 5
console.log(memoizedAdd(2, 3)); // 5 (from cache)
复制代码

7. Classes and Inheritance

Classes and inheritance refer to techniques for organizing code using concepts from object-oriented programming. This technique can be used to make code more modular and maintainable.

// 类和继承示例:使用类和继承实现动物类和猫类
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  speak() {
    console.log("I am an animal.");
  }
}
class Cat extends Animal {
  constructor(name, age, color) {
    super(name, age);
    this.color = color;
  }
  speak() {
    console.log("Meow!");
  }
}
const cat = new Cat("Fluffy", 2, "black");
复制代码

8. Generator

A Generator is a special function that suspends and resumes execution and can be used to generate iterators. Sample code:

function* generate() {
  yield 1;
  yield 2;
  yield 3;
}
const iterator = generate();
console.log(iterator.next()); // 输出 { value: 1, done: false }
console.log(iterator.next()); // 输出 { value: 2, done: false }
console.log(iterator.next()); // 输出 { value: 3, done: false }
console.log(iterator.next()); // 输出 { value: undefined, done: true }
复制代码

9. Proxy

Proxy is an object proxy mechanism that can intercept operations such as object access, assignment, and deletion, and can be used to implement functions such as data verification and data caching. Sample code:

const user = {
  name: 'John',
  age: 30,
};
const proxy = new Proxy(user, {
  get(target, key) {
    console.log(`Getting ${key} value.`);
    return target[key];
  },
  set(target, key, value) {
    console.log(`Setting ${key} value to ${value}.`);
    target[key] = value;
  },
});
console.log(proxy.name); // 输出 "Getting name value." 和 "John"
proxy.age = 40; // 输出 "Setting age value to 40."
复制代码

10. Reflect

Reflect is an object reflection mechanism, which provides a series of methods for manipulating objects, and can be used to replace some functions that can only be realized through methods on Object. Sample code:

const user = {
  name: 'John',
  age: 30,
};
console.log(Reflect.has(user, 'name')); // 输出 true
console.log(Reflect.get(user, 'name')); // 输出 "John"
console.log(Reflect.set(user, 'age', 40)); // 输出 true
console.log(user.age); // 输出 40
复制代码

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/130333992
Recommended