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

1. typeof && instanceof #1

Open
linrunzheng opened this issue Aug 4, 2021 · 0 comments
Open

1. typeof && instanceof #1

linrunzheng opened this issue Aug 4, 2021 · 0 comments
Labels

Comments

@linrunzheng
Copy link
Owner

linrunzheng commented Aug 4, 2021

/*
* 对于构造函数,有一个prototype指向它的原型
* 对于实例,同样有一个__proto__指向它的原型
* 如果不考虑继承,只需判断实例的__proto__是否等于构造函数的prototype
* 由于实例的__proto__也是一个对象,也即一个实例,所以实例的__proto__也有它的实__proto__
* 所以需要一直向上遍历到找到了,或者__proto__为null则停止
* 

function isInstanceOf(instance, ctor) {
  var ctorProto = ctor.prototype;
  var insProto = instance.__proto__;

  while (insProto) {
    if (insProto === ctorProto) {
      return true;
    } else {
      insProto = insProto.__proto;
    }
  }

  return false;
}
typeof :  js底层在存储变量时,会在变量机器码的前三位存储变量对应的类型,比如对象 ->000,字符串-> 100,通过前三位即可推断出变量的类型。由于null的机器码都是000000000....,因此typeof在判断null类型时也返回了object类型
@linrunzheng linrunzheng added the js label Aug 4, 2021
@linrunzheng linrunzheng pinned this issue Aug 4, 2021
@linrunzheng linrunzheng unpinned this issue Aug 4, 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