1、手写 new 的过程
const myNew = (fn, ...args) => {
const obj = {}
obj.__proto__ = fn.prototype
fn.apply(obj, args)
return obj
}
2、instanceof关键字
const myInstanceof = (left, right) {
if (typeof left !== 'object' || left === null) return false
let proto = Object.getPrototypeOf(left)
while (true) {
if (proto == null) return false
if (proto == right.prototype) return true
proto = Object.getPrototypeOf(proto)
}
}
console.log(myInstanceof("111", String))
console.log(myInstanceof(new String("111"), String))
详见: 浅谈 instanceof 原理
3、防抖函数
const debounce = (func, wait = 500) => {
let timer = 0
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
4、节流函数
const throttle = (func, wait = 500) => {
let lastTime = 0
return function(...args) {
let now = +new Date()
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}
setInterval(
throttle(() => {
console.log(1)
}, 3000),
1
)
5、手写 call()
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
const args = [...arguments].slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
6、手写 apply()
Function.prototype.apply = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
7、手写 bind()
Function.prototype.bind = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
return function F() {
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
详见: call、apply和bind的区别以及源码解析
8、数组去重
const quchong1 = (arr) => {
const newArr = []
arr.reduce((pre, next) => {
if (!pre[next]) {
pre[next] = 1
newArr.push(next)
}
return pre
}, {})
return newArr
}
const quchong2 = (arr) => {
return [...new Set(arr)]
}
9、数组对象去重
let arr = [{
key:
value:
}, {
key:
value:
}, {
key:
value:
}, {
key:
value:
}, {
key:
value:
}, {
key:
value:
}];
let obj = {};
arr = arr.reduce((item, next) => {
obj[next.key] ?
return item;
}, []);
console.log(arr); // [{key: "01", value: "西施"},{key: "02", value: "王昭君"},{key: "03", value: "杨玉环"},{key: "04", value: "貂蝉"}]
10、简易版深拷贝
export const deepEqual = (x, y) => {
if (x === y) {
return true;
} else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length !== Object.keys(y).length) {
return false;
}
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
if (!deepEqual(x[prop], y[prop])) return false;
} else {
return false;
}
}
return true;
} else {
return false;
}
}
详见: JavaScript 中,如何判断两个对象是否相等?