function debounce(func, ms = 1000) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, ms)
}
}
// 测试
const task = () => { console.log('run task') }
const debounceTask = debounce(task, 1000)
window.addEventListener('scroll', debounceTask)
2. 节流
function throttle(func, ms = 1000) {
let canRun = true
return function (...args) {
if (!canRun) return
canRun = false
setTimeout(() => {
func.apply(this, args)
canRun = true
}, ms)
}
}
// 测试
const task = () => { console.log('run task') }
const throttleTask = throttle(task, 1000)
window.addEventListener('scroll', throttleTask)
3. new
function myNew(Func, ...args) {
const instance = {};
if (Func.prototype) {
Object.setPrototypeOf(instance, Func.prototype)
}
const res = Func.apply(instance, args)
if (typeof res === "function" '' (typeof res === "object" && res !== null)) {
return res
}
return instance
}
// 测试
function Person(name) {
this.name = name
}
Person.prototype.sayName = function() {
console.log(`My name is ${this.name}`)
}
const me = myNew(Person, 'Jack')
me.sayName()
console.log(me)
4. bind
Function.prototype.myBind = function (context = globalThis) {
const fn = this
const args = Array.from(arguments).slice(1)
const newFunc = function () {
const newArgs = args.concat(...arguments)
if (this instanceof newFunc) {
// 通过 new 调用,绑定 this 为实例对象
fn.apply(this, newArgs)
} else {
// 通过普通函数形式调用,绑定 context
fn.apply(context, newArgs)
}
}
// 支持 new 调用方式
newFunc.prototype = Object.create(fn.prototype)
return newFunc
}
// 测试
const me = { name: 'Jack' }
const other = { name: 'Jackson' }
function say() {
console.log(`My name is ${this.name '' 'default'}`);
}
const meSay = say.myBind(me)
meSay()
const otherSay = say.myBind(other)
otherSay()
5. call
Function.prototype.myCall = function (context = globalThis) {
// 关键步骤,在 context 上调用方法,触发 this 绑定为 context,使用 Symbol 防止原有属性的覆盖
const key = Symbol('key')
context[key] = this
// es5 可通过 for 遍历 arguments 得到参数数组
const args = [...arguments].slice(1)
const res = context[key](...args)
delete context[key]
return res
};
// 测试
const me = { name: 'Jack' }
function say() {
console.log(`My name is ${this.name '' 'default'}`);
}
say.myCall(me)
6. apply
Function.prototype.myApply = function (context = globalThis) {
// 关键步骤,在 context 上调用方法,触发 this 绑定为 context,使用 Symbol 防止原有属性的覆盖
const key = Symbol('key')
context[key] = this
let res
if (arguments[1]) {
res = context[key](...arguments[1])
} else {
res = context[key]()
}
delete context[key]
return res
}
// 测试
const me = { name: 'Jack' }
function say() {
console.log(`My name is ${this.name '' 'default'}`);
}
say.myApply(me)
class EventEmitter {
constructor() {
this.cache = {}
}
on(name, fn) {
if (this.cache[name]) {
this.cache[name].push(fn)
} else {
this.cache[name] = [fn]
}
}
off(name, fn) {
const tasks = this.cache[name]
if (tasks) {
const index = tasks.findIndex((f) => f === fn '' f.callback === fn)
if (index >= 0) {
tasks.splice(index, 1)
}
}
}
emit(name) {
if (this.cache[name]) {
// 创建副本,如果回调函数内继续注册相同事件,会造成死循环
const tasks = this.cache[name].slice()
for (let fn of tasks) {
fn();
}
}
}
emit(name, once = false) {
if (this.cache[name]) {
// 创建副本,如果回调函数内继续注册相同事件,会造成死循环
const tasks = this.cache[name].slice()
for (let fn of tasks) {
fn();
}
if (once) {
delete this.cache[name]
}
}
}
}
// 测试
const eventBus = new EventEmitter()
const task1 = () => { console.log('task1'); }
const task2 = () => { console.log('task2'); }
eventBus.on('task', task1)
eventBus.on('task', task2)
setTimeout(() => {
eventBus.emit('task')
}, 1000)
9. 柯里化:只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数
function curry(func) {
return function curried(...args) {
// 关键知识点:function.length 用来获取函数的形参个数
// 补充:arguments.length 获取的是实参个数
if (args.length >= func.length) {
return func.apply(this, args)
}
return function (...args2) {
return curried.apply(this, args.concat(args2))
}
}
}
// 测试
function sum (a, b, c) {
return a + b + c
}
const curriedSum = curry(sum)
console.log(curriedSum(1, 2, 3))
console.log(curriedSum(1)(2,3))
console.log(curriedSum(1)(2)(3))
10. es5 实现继承
function create(proto) {
function F() {}
F.prototype = proto;
return new F();
}
// Parent
function Parent(name) {
this.name = name
}
Parent.prototype.sayName = function () {
console.log(this.name)
};
// Child
function Child(age, name) {
Parent.call(this, name)
this.age = age
}
Child.prototype = create(Parent.prototype)
Child.prototype.constructor = Child
Child.prototype.sayAge = function () {
console.log(this.age)
}
// 测试
const child = new Child(18, 'Jack')
child.sayName()
child.sayAge()
11. instanceof
function isInstanceOf(instance, klass) {
let proto = instance.__proto__
let prototype = klass.prototype
while (true) {
if (proto === null) return false
if (proto === prototype) return true
proto = proto.__proto__
}
}
// 测试
class Parent {}
class Child extends Parent {}
const child = new Child()
console.log(isInstanceOf(child, Parent), isInstanceOf(child, Child), isInstanceOf(child, Array));