How does instanceof work in JavaScript? -
in following code sample both checks of obj2 , obj3 @ end instanceof return true if ways there constructed different , results of returning name property different.
var obj1 = function() { this.name = "foo1"; }; obj1.prototype.name = "foo1onprot"; var obj1 = new obj1(); var obj2 = function() {}; obj2.prototype = new obj1(); obj2.prototype.constructor = obj2; var obj2 = new obj2(); var obj3 = function() {}; obj3.prototype = object.create(obj1.prototype); obj3.prototype.constructor = obj3; var obj3 = new obj3(); console.dir(obj1); console.log("obj1.name: " + obj1.name); console.dir(obj2); console.log("obj2.name: " + obj2.name); console.dir(obj3); console.log("obj3.name: " + obj3.name); console.log("obj2 instanceof obj1: " + (obj2 instanceof obj1)); console.log("obj3 instanceof obj1: " + (obj3 instanceof obj1));
result of run in chrome:
obj1 name: "foo1" __proto__: object constructor: function () { name: "foo1onprot" __proto__: object obj1.name: foo1 obj2 __proto__: obj1 constructor: function () {} name: "foo1" __proto__: object constructor: function () { name: "foo1onprot" __proto__: object obj2.name: foo1 obj3 __proto__: object constructor: function () {} __proto__: object constructor: function () { name: "foo1onprot" __proto__: object obj3.name: foo1onprot obj2 instanceof obj1: true obj3 instanceof obj1: true
what best way recognize obj2 , obj3 different? how instanceof work?
most simply: obj instanceof constructor
yields true
when obj
has constructor
's prototype in it's constructor/prototype chain. in other words, asking engine whether obj
can treated instance of constructor
/ whether obj
behaves constructor
object.
there small handful of syntaxes allow put constructor
's prototype in obj
's prototype chain. , of them cause obj instanceof constructor
true
. in examples, both obj2
, obj3
have obj1
in prototype chain.
so, when ask javascript engine whether either obj2
or obj3
behave instance of obj1
, javascript assumes true
-- case wherein wouldn't if you've overridden obj1
's behavior down line.
Comments
Post a Comment