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__
}
}