new
关键字一起使用,这样每次调用都会创建一个新的对象,并将其this
上下文绑定到新创建的对象上。- function Person(name, age) {
- this.name = name;
- this.age = age;
- }
- let person = new Person('Tom', 25);
- let lazySingleton = function() {
- let instance;
- return function() {
- if (!instance) {
- instance = new SomeExpensiveObject();
- }
- return instance;
- };
- }();
-
- // 第一次调用时初始化,后续调用返回同一实例
- let obj = lazySingleton();
let element = $('#myElement').addClass('active').show().css('color', 'red');
- setTimeout(function callback() {
- console.log('This is a callback function');
- }, 1000);
.map()
、.filter()
、.reduce()
等函数都是高阶函数。- let numbers = [1, 2, 3, 4, 5];
- let squared = numbers.map(function square(n) {
- return n * n;
- });
- function curry(func) {
- return function curried(...args) {
- if (args.length >= func.length) {
- return func.apply(this, args);
- } else {
- return function(...moreArgs) {
- return curried.apply(this, [...args, ...moreArgs]);
- };
- }
- };
- }
-
- let add = curry((a, b, c) => a + b + c);
- let sumThree = add(1)(2)(3); // returns 6
- function throttle(fn, delay) {
- let lastCall = 0;
- return function throttled() {
- const now = Date.now();
- if (now - lastCall > delay) {
- fn.apply(this, arguments);
- lastCall = now;
- }
- };
- }
-
- window.addEventListener('scroll', throttle(handleScroll, 100));
- function debounce(fn, delay) {
- let timerId;
- return function debounced() {
- clearTimeout(timerId);
- timerId = setTimeout(() => {
- fn.apply(this, arguments);
- }, delay);
- };
- }
-
- window.addEventListener('resize', debounce(handleResize, 200));
- function memoize(func) {
- let cache = new Map();
- return function memorized(...args) {
- if (cache.has(args)) {
- return cache.get(args);
- } else {
- let result = func.apply(this, args);
- cache.set(args, result);
- return result;
- }
- };
- }
-
- let expensiveComputation = memoize(function compute(a, b) {
- // 这里是一些复杂的计算...
- return a * b;
- });
setTimeout
模拟类似效果,让函数暂停一段时间后再继续执行。- async function sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-
- async function sleepyFunction() {
- console.log('Start');
- await sleep(2000);
- console.log('Wake up after 2 seconds');
- }
- function add(a, b) {
- return a + b;
- }
-
- let addToFive = _.partial(add, 5); // 使用lodash库的_.partial
- console.log(addToFive(3)); // 输出8
以上概念在现代JavaScript开发中非常常见,合理运用这些技术可以极大提升代码的效率和可读性。