When looking at the code provided, it can be seen that both checks of obj2 and obj3 at the end using instanceof return true even though they were constructed differently and have different results when returning the name property.
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 running the code 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
To distinguish between obj2 and obj3, what is the most effective approach? How does the instanceof operator actually work?