How to Natively Implement instanceOf in JavaScript
<p>The <code>instanceof</code> operator tests to see if the <code>prototype</code> property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.</p>
<p>Interviewer: to write a fakeInstanceOf, you must meet the following test cases:</p>
<pre>
function fakeInstanceOf (instance, parent): Boolean {}
//=> true
fakeInstanceOf([], Array)
//=> true
fakeInstanceOf([], Object)
//=> true
fakeInstanceOf(x => x, Object)
//=> false
fakeInstanceOf('hello', Object)</pre>
<p>The following is a reference</p>
<pre>
function fakeInstanceOf (instance, parent) {
if (typeof(instance) !== 'object' && typeof(instance) !== 'function') {
return false
}
let proto = instance?.__proto__ || null
while (true) {
if (proto === null) { return false }
if (proto === parent.prototype) { return true }
proto = proto.__proto__
}
}</pre>
<p><a href="https://javascript.plainenglish.io/how-to-natively-implement-instanceof-in-javascript-15d6eca383c2">Website</a></p>