I've read about Javascript's instanceof operator and wanted to test it out. I've written this code:
function first() {};
first.prototype.hello = function hello() {
console.log("hello");
}
var second = {};
second.prototype = Object.create(first.prototype);
console.log(second instanceof first); //should've output true
second.hello();
This doesn't work as expected (by me). What I thought when writing this fragment:
instanceof takes a function (first in this case) as its right hand operand and an object as its left hand operand. Then it checks whether the given function's prototype appears in any part of the object's prototype chain. first is the function, hello is some function added to first's prototype. second's prototype is assigned a new object which has a prototype link to first.prototype so when second instanceof first is executed, it cannot find link to first.prototype object on second directly so it follows prototype link to second.prototype which has that link.
When I run this in Chrome this is the result:
false Uncaught TypeError: second.hello is not a function at main.js:13
Could you please help me out with this?
second = new first()- isn't that what you're trying to achieve? that patterns seems to be trying to subclassfirstas classsecond- but you're "doing it wrong"™second instanceof firstreturns false, andsecond.hello()yieldsUncaught TypeError: second.hello is not a function", and indicated the corresponding line in your code.