JavaScript基础之new、instanceof操作符的实现

JavaScript基础之new、instanceof操作符的实现

1. new的实现

new做了一下以下操作:
1. 创建了一个对象(内存中开辟空间);
2. 将这个创建的对象的原型对象(proto)指向构造函数的原型对象(prototype);
3. 让当前构造函数的this指向创建的对象,并执行构造函数;
4. 执行构造函数的返回值如果是引用类型,那么直接返回,否则把创建的对象返回。

function myNew () {
  var Constructor = Array.prototype.shift.call(arguments)
  if (typeof Constructor !== 'function') {
    throw new TypeError('Constructor muste be a function !')
  }
  var obj = {}
  obj.__proto__ = Constructor.prototype
  var res = Constructor.apply(obj, arguments)
  return res instanceof Object ? res : obj
}

2. instanceof的实现

A instanceof B判断实例A是否在构造函数实例所在的原型链上

function instanceOf (A, B) {
  if (typeof B !== 'function') {
    throw new TypeError('B must type of function')
  }
  A = A.__proto__
  B = B.prototype
  while (true) {
    // 一直找到Object.prototype.__proto__
    if (A === null) return false
    if (A === B) return true
    A = A.__proto__
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值