学习中,文档持续更新~
实现
-
函数柯里化
-
冒泡排序的复杂度是多少?快排呢
-
如何实现快排?
-
如何实现二分查找?(迭代版和递归版,问那个效率高一些)
-
JavaScript递归转循环?
-
如何用原生JS实现一个队列
-
如何实现一个栈
-
如何实现一个同花顺?写代码如何实现?(七张牌同一花色并且数字相连)
-
数组 flat、去重及排序
-
设计异步清空队列
-
手写设计模式
-
手写new
// 第一个参数必须是方法体 function myNew(func, ...args) { // 1. 判断方法体 if (typeof func !== 'function') { throw '第一个参数必须是方法体'; } // 2. 创建新对象 const obj = {}; // 3. 这个对象的 __proto__ 指向 func 这个类的原型对象 // 即实例可以访问构造函数原型(constructor.prototype)所在原型链上的属性 obj.__proto__ = Object.create(func.prototype); // 为了兼容 IE 可以让步骤 2 和 步骤 3 合并 // const obj = Object.create(func.prototype); // 4. 通过 apply 绑定 this 执行并且获取运行后的结果 let result = func.apply(obj, args); // 5. 如果构造函数返回的结果是引用数据类型,则返回运行后的结果 // 否则返回新创建的 obj const isObject = typeof result === 'object' && result !== null; const isFunction = typeof result === 'function'; return isObject || isFunction ? result : obj; } // 测试 function Person(name) { this.name = name; } // 用来测试第 2 点和第 3 点 Person.prototype.sayName = function() { console.log(`My name is ${this.name}`); } const me = myNew(Person, 'test'); me.sayName(); // My name is test console.log(me); // Person {name: 'test'}
-
手写call
-
手写bind
-
手写apply
-
手写promise
-
手写instanceof
-
手写typeof
-
手写Object.create
-
手写Object.assign()
-
手写防抖
试着函数柯里化的形式封装一个防抖函数:
<html>
<input type="text" id="input" name=""/>
<input type="text" id="input2" name=""/>
</html>
<script type="text/javascript">
function foo() {
console.log(...arguments);
}
function debounce(fn, delay){
return function() {
let args = arguments; // 获取'parameter1','parameter2','parameter3'
let timer = null;
return function(){
let _this = this;
let E = arguments; // 获取Even
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(_this, [...E,...args]);
}, delay)
}
}
}
// 防抖+节流
function debounce2(fn, delay){
return function() {
let args = arguments; // 获取'parameter1','parameter2','parameter3'
let timer = null;
let last = 0
return function(){
let _this = this;
let E = arguments; // 获取Even
let now = new Date();
if (now - last < delay){
clearTimeout(timer);
timer = setTimeout(function(){
last = now;
fn.apply(_this, [...E,...args]);
}, delay)
} else {
// 这个时候表示时间到了,必须给响应
last = now;
fn.apply(_this, [...E,...args]);
}
}
}
};
document.getElementById('input').addEventListener('keyup', debounce(foo,2000)('parameter1','parameter2','parameter3'));
document.getElementById('input2').addEventListener('keyup', debounce2(foo,2000)('parameter1','parameter2','parameter3'));
</script>
-
手写节流
function throttle(fn, delay){
return function (){
let args = arguments; // 获取'parameter1','parameter2','parameter3'
let timer = null;
return function () {
if (timer) {
return;
}
let E = arguments; // 获取Even
let _this = this;
timer = setTimeout(()=>{
timer = null;
fn.apply(_this, [...E,...args]);
},delay);
}
}
}
document.addEventListener('scroll',throttle(foo,1000)('parameter1','parameter2','parameter3'));