fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

手写 instanceof

Open habc0807 opened this issue 4 years ago • 2 comments

habc0807 avatar Sep 01 '20 07:09 habc0807

function instanceof(L, R) { 
    L = L.__proto__
    const O = R.prototype
    
    while(true) {
        if (L === null)  return false
        if (L === O)  return true
        L = L.__proto__
    }
}

左的__proto__存在,是遍历条件,L=== R.prototype 和 L===null 是终止条件

habc0807 avatar Sep 01 '20 10:09 habc0807

function instance_of(A, B) {
  const current = Object.getPrototypeOf(A);
  if (current === null) return false;
  if (current === B.prototype) return true;
  return instance_of(current, B);
}

kayac-chang avatar Mar 18 '24 08:03 kayac-chang