实现new
new Foo的过程
1、创建一个新对象,他的原型__proto__指向构造函数的prototype
2、执行构造函数,重新指定this为该新对象,并传入对应参数
3、返回一个对象,如果构造函数返回一个对象,则返回这个对象,否则返回创建的新对象
编码如下:
// 模拟new的实现let newMock = function () {let argus = Array.prototype.slice.apply(arguments);let Foo = argus.shift();let target = Object.create(Foo.prototype);let foo = Foo.apply(target, argus);if (typeof foo === 'object') {// 比如构造函数返回了一个Object,工厂模式之类的return foo;} else {return target;}}// 构造函数let Person = function (name) {this.name = `i am ${name}`;this.say = function () {console.log(this)}}// 使用let p = newMock(Person, 'www')console.log(p instanceof Person) // === true 说明newMock使用成功
实现Promise
实现bind
实现节流和防抖
/*** 防抖函数* 函数停止1s后执行* @param func* @param wait* @returns {Function}*/const debounce = (func, wait) => {let timeout;return function () {let context = this;let argus = arguments;if (timeout) clearTimeout(timeout);timeout = setTimeout(() => {func.apply(context, argus)}, wait);}};/*** 节流函数* 1s执行一次目标函数* @param func* @param wait* @returns {Function}*/const throttle = (func, wait) => {let previous = 0;return function () {let now = Date.now();let context = this;let argus = arguments;if (now - previous > wait) {func.apply(context, argus);previous = now;}}};
