手写new 方法
function myNew(Fn, ...args) {
const Obj = {};
if(typeof(Fn) !== "function" ) return;
Obj.__proto__ = Fn.prototype; // 继承 prototype
const res = Fn.call(Obj, ...args); //改变this指向
if(typeof res === "object" && res !== null) return res;
return Obj;
}
function myNew(Func, ...args) {
// 创建一个空的对象,将实例化对象的原型指向构造函数的原型对象
const newObj= Object.create(Func.prototype);
// 将构造函数的this指向实例化对象
const res = Func.call(newObj, ...args);
//判断返回值
return (typeof res === 'object' && res !== null ) ? res : newObj
}
手写flat 方法(递归)
function flat(arr, count = 1) {
let newArr = count > 0
?
arr.reduce(
(pre, cur) =>
pre.concat(Array.isArray(cur) ? flat(cur, count - 1) : cur),
[])
:
arr.slice();
}
function* flat(arr, count= 1) {
if (typeof(count) !== number && count>0) throw new Error("Expect to get an integer greater than 0!")
for (const item of arr) {
if (Array.isArray(item) && count> 0) { // num > 0
yield* flat(item, count- 1);
} else {
yield item;
}
}
}
// 调用 Generator 函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象。
// 也就是遍历器对象(Iterator Object)。所以我们要用一次扩展运算符得到结果
[...flat(arr, Infinity)]
Array.prototype.myFlat = function(num = 1) {
if (!Number(num) || Number(num) < 0) {
return this;
}
let arr = [];
this.forEach(item => {
if (Array.isArray(item)) {
arr = arr.concat(item.fakeFlat(--num));
} else {
arr.push(item);
}
});
return arr;
};
手写instanceof方法
//while
function myInstanceof (left, right) {
let proto = Object.getPrototypeOf(left), prototype = right.prototype;
while (proto !== null && proto !== undefined) {
if (proto === prototype) {
return true;
} else {
proto = Object.getPrototypeOf(proto);
}
}
return false;
}
// 递归
function myInstanceof (left, right) {
// 得到检测的类型 和被检测的prototype
const proto = Object.getPrototypeOf(left), prototype = right.prototype;
if (proto === null || proto === undefined) {
return false;
} else if (proto === prototype) {
return true;
} else {
// 递归 检测
return myInstanceof(Object.getPrototypeOf(proto), right);
}
}
参考文献
如何手写一个js中的New方法
面试官连环追问:数组拍平(扁平化) flat 方法实现
手写instanceof (详解原型链) 和 实现绑定解绑和派发的事件类
本文介绍了JavaScript中手写实现new、flat和instanceof方法的详细过程,包括如何创建对象并继承原型、数组的递归扁平化以及判断对象是否为某个构造函数的实例。通过这些手写实现,深入理解JavaScript核心概念。
256

被折叠的 条评论
为什么被折叠?



