JavaScript常用手写函数实现
掌握JavaScript基础函数的手写实现,对于理解语言特性和应对技术面试都很有帮助。下面介绍一些常用的手写函数实现。
防抖函数 (debounce)
防抖函数的作用是让一个函数在连续触发时只执行最后一次。
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 使用示例
const searchInput = document.getElementById('search');
const handleSearch = debounce(function(keyword) {
console.log('搜索关键词:', keyword);
}, 300);
searchInput.addEventListener('input', (e) => {
handleSearch(e.target.value);
});节流函数 (throttle)
节流函数让一个函数在一定时间内只执行一次。
function throttle(fn, delay) {
let canRun = true;
return function(...args) {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, args);
canRun = true;
}, delay);
};
}
// 使用示例
window.addEventListener('scroll', throttle(function() {
console.log('滚动处理');
}, 100));实现new操作符
了解new操作符背后的原理。
function myNew(Fn, ...args) {
// 创建新对象,继承构造函数的原型
const obj = Object.create(Fn.prototype);
// 执行构造函数,绑定this
const result = Fn.apply(obj, args);
// 如果构造函数返回对象,就返回这个对象,否则返回新创建的对象
return result instanceof Object ? result : obj;
}
// 使用示例
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
const person = myNew(Person, '张三');
person.sayHello(); // Hello, 张三实现instanceof
理解原型链的查找机制。
function myInstanceof(obj, Fn) {
let proto = obj.__proto__;
while (proto) {
if (proto === Fn.prototype) return true;
proto = proto.__proto__;
}
return false;
}
// 使用示例
console.log(myInstanceof([], Array)); // true
console.log(myInstanceof({}, Object)); // true深拷贝函数
实现一个完整的深拷贝功能。
function deepClone(obj, map = new WeakMap()) {
// 如果不是对象或者是null,直接返回
if (typeof obj !== 'object' || obj === null) return obj;
// 解决循环引用问题
if (map.has(obj)) return map.get(obj);
// 创建新的对象或数组
let result = Array.isArray(obj) ? [] : {};
map.set(obj, result);
// 递归拷贝所有属性
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key], map);
}
}
return result;
}
// 使用示例
const original = {
name: '张三',
hobbies: ['篮球', '游泳'],
info: { age: 25 }
};
const cloned = deepClone(original);数组扁平化
将多维数组转换为一维数组。
function flatten(arr) {
return arr.reduce((prev, curr) =>
prev.concat(Array.isArray(curr) ? flatten(curr) : curr),
[]);
}
// 使用示例
const nestedArray = [1, [2, [3, 4], 5]];
console.log(flatten(nestedArray)); // [1, 2, 3, 4, 5]函数柯里化
将多参数函数转换为一系列单参数函数。
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return (...args2) => curried.apply(this, args.concat(args2));
}
};
}
// 使用示例
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6实现bind方法
理解函数绑定的原理。
Function.prototype.myBind = function(context, ...args) {
const fn = this;
return function(...args2) {
return fn.apply(context, [...args, ...args2]);
};
};
// 使用示例
const person = {
name: '李四'
};
function introduce(age, city) {
console.log(`我是${this.name}, ${age}岁, 来自${city}`);
}
const boundFunc = introduce.myBind(person, 25);
boundFunc('北京'); // 我是李四, 25岁, 来自北京实现call方法
Function.prototype.myCall = function(context, ...args) {
context = context || window;
const fn = Symbol();
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
};
// 使用示例
const obj = { name: '王五' };
function showName(age) {
console.log(this.name, age);
}
showName.myCall(obj, 30); // 王五 30实现apply方法
Function.prototype.myApply = function(context, args = []) {
context = context || window;
const fn = Symbol();
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
};
// 使用示例
const obj = { name: '赵六' };
function showInfo(age, city) {
console.log(this.name, age, city);
}
showInfo.myApply(obj, [28, '上海']); // 赵六 28 上海冒泡排序
理解基础的排序算法。
function bubbleSort(arr) {
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// 使用示例
console.log(bubbleSort([64, 34, 25, 12, 22, 11, 90]));选择排序
另一种基础排序算法。
function selectionSort(arr) {
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
// 使用示例
console.log(selectionSort([64, 25, 12, 22, 11]));学习建议
理解原理:不要死记硬背,要理解每个函数的设计思想
多练习:亲手实现这些函数,加深理解
思考边界情况:考虑各种异常情况的处理
性能优化:思考如何让函数更高效
掌握这些基础函数的手写实现,不仅有助于通过技术面试,更能加深对JavaScript语言特性的理解。在实际开发中,虽然我们通常使用现成的方法,但了解其底层原理对于解决复杂问题和调试代码都有很大帮助。
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!