Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2021/01/28 - typeof和instanceof的原理及区别 #33

Open
lxinr opened this issue Jan 28, 2021 · 0 comments
Open

2021/01/28 - typeof和instanceof的原理及区别 #33

lxinr opened this issue Jan 28, 2021 · 0 comments
Labels

Comments

@lxinr
Copy link
Owner

lxinr commented Jan 28, 2021

typeof

typeof操作符返回一个字符串,表示未经计算的操作数的类型

  • 对于基本类型,除null特殊返回object以外,其他的都能返回其正确的类型
  • 对于引用类型,除了function类型会返回function以外,其他一律返回object类型

因块级作用域声明letconst会导致暂时性死区,因此在这些变量声明前使用typeof执行会抛出ReferenceError异常

typeof info // Uncaught ReferenceError: info is not defined
typeof req // Uncaught ReferenceError: Cannot access 'req' before initialization
let info = '111'
const req = 2

instanceof

instanceof运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

// 语法
object instanceof constructor 
// instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上
// 即判断object.__proto__ === constructor.prototype是否为true

实现

function instanceof(target, v) {
  if(typeof target !== 'object' || target === null) return false
  // Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)
  let proto = Object.getPrototypeOf(target)
  // 一直往上找,直到找到相同的原型对象返回true,或者直到null,返回false
  while(true) {
    if(proto === null) return false
    if(proto === v.prototype) return true
    proto === Object.getPrototypeOf(proto)
  }
}
@lxinr lxinr added the JS基础 label Jan 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant