关于JS中一些重要的api实现, 巩固你的原生JS功底(二)

未结 0 2947
VIP1 2019年09月20日
悬赏:20积分

六、实现new关键字
核心要点:

1、创建一个全新的对象,这个对象的__proto__要指向构造函数的原型对象
2、执行构造函数
3、返回值为object类型则作为new方法的返回值返回,否则返回上述全新对象


function myNew(fn, ...args) {
let instance = Object.create(fn.prototype);
let res = fn.apply(instance, args);
return typeof res === 'object' ? res: instance;
}

七、实现instanceof的作用
核心要点:原型链的向上查找。

function myInstanceof(left, right) {
let proto = Object.getPrototypeOf(left);
while(true) {
if(proto == null) return false;
if(proto == right.prototype) return true;
proto = Object.getPrototypeof(proto);
}
}

八、实现单例模式
核心要点: 用闭包和Proxy属性拦截

function proxy(func) {
let instance;
let handler = {
constructor(target, args) {
if(!instance) {
instance = Reflect.constructor(fun, args);
}
return instance;
}
}
return new Proxy(func, handler);
}

九、实现防抖功能
核心要点:

如果在定时器的时间范围内再次触发,则重新计时。

const debounce = (fn, delay) => {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};




转自 掘金 神三元
链接:https://juejin.im/post/5d635566e51d4561e224a360

回帖
  • 还没有人回复
本周热议
没有相关数据
layui

微信扫码关注 网盟开源 公众号