当前位置:首页 > JavaScript

用js实现js内置函数

2026-02-02 12:33:00JavaScript

用js实现js内置函数

用js实现js内置函数

实现 JavaScript 内置函数

以下是几个常见 JavaScript 内置函数的自定义实现示例:

Array.prototype.map

Array.prototype.myMap = function(callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(callback(this[i], i, this));
  }
  return result;
};

// 使用示例
const arr = [1, 2, 3];
const doubled = arr.myMap(x => x * 2); // [2, 4, 6]

Array.prototype.filter

Array.prototype.myFilter = function(callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};

// 使用示例
const nums = [1, 2, 3, 4];
const evens = nums.myFilter(x => x % 2 === 0); // [2, 4]

Array.prototype.reduce

Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = initialValue !== undefined ? initialValue : this[0];
  let startIndex = initialValue !== undefined ? 0 : 1;

  for (let i = startIndex; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};

// 使用示例
const numbers = [1, 2, 3, 4];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0); // 10

Function.prototype.bind

Function.prototype.myBind = function(context, ...args) {
  const fn = this;
  return function(...innerArgs) {
    return fn.apply(context, [...args, ...innerArgs]);
  };
};

// 使用示例
const person = { name: 'John' };
function greet(greeting) {
  return `${greeting}, ${this.name}`;
}
const boundGreet = greet.myBind(person, 'Hello');
boundGreet(); // "Hello, John"

Object.assign

Object.myAssign = function(target, ...sources) {
  sources.forEach(source => {
    for (const key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  });
  return target;
};

// 使用示例
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = Object.myAssign({}, obj1, obj2); // { a: 1, b: 2 }

Promise

class MyPromise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled';
        this.value = value;
        this.onFulfilledCallbacks.forEach(fn => fn());
      }
    };

    const reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.reason = reason;
        this.onRejectedCallbacks.forEach(fn => fn());
      }
    };

    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }
  }

  then(onFulfilled, onRejected) {
    const promise2 = new MyPromise((resolve, reject) => {
      if (this.state === 'fulfilled') {
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else if (this.state === 'rejected') {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else {
        this.onFulfilledCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onFulfilled(this.value);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
        this.onRejectedCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onRejected(this.reason);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
      }
    });

    return promise2;
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(new TypeError('Chaining cycle detected'));
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}

这些实现展示了 JavaScript 内置函数的基本原理,但要注意实际的内置函数实现可能更复杂,包含更多边界情况处理。

标签: 函数js
分享给朋友:

相关文章

jquery函数

jquery函数

jQuery 函数概述 jQuery 是一个快速、简洁的 JavaScript 库,通过封装原生 JavaScript 功能,简化 DOM 操作、事件处理、动画和 AJAX 等任务。其核心函数 $()…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的JWT令牌…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js 实现验证码

js 实现验证码

实现验证码的 JavaScript 方法 生成随机验证码 验证码通常由随机字符(数字、字母或混合)组成。以下代码生成一个 6 位随机验证码(数字和字母混合): function generateCa…

js sort 实现

js sort 实现

数组排序基础方法 JavaScript 数组的 sort() 方法默认按照字符串 Unicode 码点顺序排序。直接调用时会将元素转为字符串再比较: const arr = [10, 2, 5, 1…

js实现点击隐藏

js实现点击隐藏

使用CSS类切换实现点击隐藏 通过添加或移除CSS类来控制元素的显示与隐藏。定义一个隐藏样式类如.hidden { display: none; },通过事件监听切换该类。 document.que…