Sometimes you think you know something, and then it turns out you really don't...
I've been doing a lot of research into the Javascript inheritance over the last few days for a talk I'm giving at a local tech group. No problem I figured, I know this stuff, I'll just brush up...
Turns out, I've lots still to learn. Here is the first thing that surprised me:
function Vehicle() {
function move() {
console.log('moving');
}
return {move: move}
}
function OtherVehicle() {
this.alsoMove = function() {
console.log('also moving')
}
}
The first method is what I've always understood the module pattern to be. The second, though I don't know it's name, I understood to be basically equivalent - just a minor syntactic variation.
Except:
(new Vehicle()) instanceof Vehicle \\ returns false
(new OtherVehicle()) instanceof OtherVehicle \\ returns true
new Vehicle() returns an 'Object'.
Looking at this, that makes sense, but it was not what I was expecting.
Can anyone explain what is going on here, why, and maybe point me at a really good resource that gets into the guts of this?
As a follow-up.
var Car = function() {
function drive() { console.log('driving') };
return {drive: drive}
}
Car.prototype = new Vehicle() //I know, Object.create preferred
(new Car).move() //undefined
// However...
var Car = function() {
this.drive = function () { console.log('driving') };
}
Car.prototype = new Vehicle();
(new Car()).move() //output 'moving'
So, the module pattern can't be used in inheritance?
Or have I just woken from the wrong side of the bed today and should go for a run before I next touch a keyboard?