手写new flat instanceOf方法

本文介绍了JavaScript中手写实现new、flat和instanceof方法的详细过程,包括如何创建对象并继承原型、数组的递归扁平化以及判断对象是否为某个构造函数的实例。通过这些手写实现,深入理解JavaScript核心概念。

手写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 (详解原型链) 和 实现绑定解绑和派发的事件类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaxLoongLvs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值