目录
instanceof
解释
instanceof 是 JavaScript 中的运算符,用于检查一个对象是否是另一个对象的实例,其实现原理如下:
当使用 instanceof 运算符时,会调用对象的 [[Symbol.hasInstance]] 方法,该方法在对象的原型链上递归查找,判断目标对象是否为指定类的实例,如果在原型链中找到指定类的原型对象,则返回 true ,否则返回 false 。
简单来说, instanceof 实现原理就是基于对象的原型链机制,通过查找对象的原型链,判断目标对象是否为指定类的实例。
本质上是对原型链( child.__proto__ 指向 parent.prototype )的一个考察。
手写实现
function myInstanceof(target, type) {
while (true) {
type = type.prototype;
target = target.__proto__;
if (target === type) {
return true;
}
if (target === null) {
return false;
}
}
}
class Test{};
const test = new Test();
console.log(myInstanceof(test, Test); // true
new 关键字
解释
new 操作符的实现步骤如下:
-
创建一个新对象
-
将构造函数的作用域赋给新对象(也就是将对象的 __proto__ 属性指向构造函数的 prototype 属性,使得 child.__proto__ 指向 parent.prototype )
-
指向构造函数中的代码,构造函数中的 this 指向该对象(也就是为这个对象添加属性和方法)
-
返回新的对象或值(要判断类型)
手写实现
function myNew(fn, ...args) {
// 步骤1、2
const newObj = Object.create(fn.prototype);
// 步骤3
const res = fn.apply(newObj, args);
// 步骤4 需要判断返回对象的类型来处理返回值
// new特性:构造函数如果返回基本数据类型,那么这个返回值并没有作用;如果返回的是一个对象,那个这个返回值会被正常使用
// 所以:如果没有返回值或是一个基本数据类型,返回创建的对象;如果是引用类型,就返回这个引用类型的对象
if (res && (typeof res === 'object' || typeof res === 'function')) {
return res;
}
return newObj;
}
const arr = myNew(Array, 1, 2, 3);
console.log(Array.isArray(arr)); // true
console.log(arr); // [1, 2, 3]