首页 > IT职业 > IT图书 > 前端 P5 最基本应该掌握的代码实现
疫情无情人有情,在去年经历互联网一系列的风波之后,我相信大家有很多的小伙伴想在今年金三银四的面试季中为自己的未来找一个好一点的公司。那么今天我们来讲解一下身为 P5 工程师需要知道的一些原理及其如何亲自手写出它的实现过程,有可能我们日常开发业务的时候用不上这些自己写的方法,但是我们我们对原理一无所知,那么在面试的时候一旦被深挖那么可能离自己心念的公司就会又远一步。
Function.prototype.myCall = function(context,...args){
context = (context ?? window) || new Object(context);
const key = Symbol();
context[key] = this;
const result = context[key](...args);
delete context[key];
return result;
}
Function.prototype.myApply = function(context) {
context = (context ?? window) || new Object(context)
const key = Symbol()
const args = arguments[1]
context[key] = this
let result
if(args) {
result = context[key](...args)
} else {
result = context[key]
}
delete context[key]
return result
}
Function.prototype.myBind = function(context, ...args) {
const fn = this
const bindFn = function (...newFnArgs) {
fn.call(
this instanceof bindFn ? this : context,
...args, ...newFnArgs
)
}
bindFn.prototype = Object.create(fn.prototype)
return bindFn
}
const deepClone = (target, cache = new WeakMap()) => {
if(target === null || typeof target !== 'object') {
return target
}
if(cache.get(target)) {
return target
}
const copy = Array.isArray(target) ? [] : {}
cache.set(target, copy)
Object.keys(target).forEach(key => copy[key] = deepClone(obj[key], cache))
return copy
}
const debounce = (fn, wait = 300, leading = true) => {
let timerId, result
return function(...args) {
timerId && clearTimeout(timerId)
if (leading) {
if (!timerId) result = fn.apply(this, args)
timerId = setTimeout(() => timerId = null, wait)
} else {
timerId = setTimeout(() => result = fn.apply(this, args), wait)
}
return result
}
}
函数停止触发后 n妙后开始执行,停止触发后继续执行一次事件
const throttle = (fn, wait = 300) => {
let timerId
return function(...args) {
if(!timerId) {
timerId = setTimeout(() => {
timerId = null
return result = fn.apply(this, ...args)
}, wait)
}
}
}
函数触发后立刻执行,停止触发后不在执行事件
const throttle = (fn, wait = 300) => {
let prev = 0
let result
return function(...args) {
let now = +new Date()
if(now - prev > wait) {
prev = now
return result = fn.apply(this, ...args)
}
}
}
ES5的继承,实质是先创造子类的实例对象,然后将再将父类的方法添加到this上。ES6的继承,先创造父类的实例对象(所以必须先调用super方法,然后再用子类的构造函数修改this。
class Super { constructor(foo) { this.foo = foo } printFoo() { console.log(this.foo) } } class Sub extends Super { constructor(foo, bar) { super(foo) this.bar = bar } }js
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3137/viewspace-2824845/ ,如需转载,请注明出处,否则将追究法律责任。