minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

3 -【经典面试】instanceof 原理 #3

Open OceanApart opened 3 years ago

OceanApart commented 3 years ago

原理及函数实现

minjs1cn commented 3 years ago

使用场景

判断某个实例是否是属于某个类型,或者是其父/祖先类型,例如:

class Animal {
  constructor() {}
}
const a = new Animal()
console.log(a instanceof Animal)

class Cat extends Animal {
  constructor(){
    super()
  }
}
const c = new Cat()
console.log(c instanceof Animal)
console.log(c instanceof Cat)
function Animal() {}
const a = new Animal()
console.log(a instanceof Animal)

function Cat() {
}
Cat.prototype = new Animal()
Cat.prototype.construtor = Cat
const c = new Cat()
console.log(c instanceof Animal)
console.log(c instanceof Cat)
function Animal() {}
Animal.prototype = {
  constructor: Animal,
  sayHi() {}
}
const a = new Animal()
console.log(a instanceof Animal)

如果需要判断基本类型,可以使用typeof
如果是对象,可以使用 Object.prototype.toString

原理

右边变量的 prototype 在左边变量的原型链上即可

function instanceTo(left, right) {
  const prototype = right.prototype
  while(true) {
    if (left === null) return false
    if (left === prototype) return true
    left = left.__proto__
  }
}

思考

console.log(String instanceof String);  // ?
console.log(Object instanceof Object);  // ?
console.log(Function instanceof Function); // ?
console.log(Function instanceof Object); // ?
minjs1cn commented 3 years ago

1、万物皆对象, 对象是 new Object 来的,null 是对象之根。每一个对象都有一个proto属性指向该对象的原型

var o = {} // new Object({})
o.__proto__ === Object.prototype
o.__proto__.__proto__ == null

2、函数是一等公民,每一个函数都有一个prototype对象

function Function() {}
Function.prototype = new Object({
  construtor: Function,
})

var String = new Function()
String.construtor == Function
var Object = new Function()
Object.construtor == Function