Skip to content

Instantly share code, notes, and snippets.

@wangziling
Created September 18, 2018 09:59
Show Gist options
  • Save wangziling/14b5dce4e30d3da881bd9ed7d0ab386d to your computer and use it in GitHub Desktop.
Save wangziling/14b5dce4e30d3da881bd9ed7d0ab386d to your computer and use it in GitHub Desktop.
instanceof 原理大概解析
// 转自:https://www.ibm.com/developerworks/cn/web/1306_jiangjj_jsinstanceof/
// instanceof 原理大概解析
function instance_of(L, R) {// L 表示左表达式,R 表示右表达式
var O = R.prototype;// 取 R 的显示原型
L = L.__proto__;// 取 L 的隐式原型
while (true) {
if (L === null)
return false;
if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true
return true;
L = L.__proto__;
}
}
// 从上方代码可以看到,只需要判断左侧对象原型链上,是否有 instanceof 右侧 构造函数 的 prototype 即可。
// 那么,可以做到:
// Foo instancof Foo === true
const Foo = Object;
Foo.__proto__ = Foo.prototype;
console.log(Foo instanceof Foo); // true
console.log(instance_of(Foo, Foo)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment