I'm having a bit of a dilemma getting my head around JS' prototypal inheritance. What I'm trying to do is:
Define an object called mod
var mod = function() { function sayGoodbye() { alert("Goodbye!"); } function saySomethingElse(message) { alert(message); } return { sayGoodbye: sayGoodbye, saySomethingElse: saySomethingElse }; };Define a prototype object called proto
var proto = { sayHello: function() { alert("Hello!"); } };Set the prototype of mod to proto
mod.prototype = proto;Call a function that constructs a new instance of mod with the proto prototype
function construct(constructor, args) { function constructorWrapper() { return constructor.apply(this, args) } constructorWrapper.prototype = constructor.prototype; return new constructorWrapper(); } var foo = construct(mod, ["Other Message 1"]); var bar = construct(mod, ["Other Message 2"]); console.dir(foo); console.dir(bar);
The construct function creates a new instance of mod correctly using the apply function but it's prototype is not proto. What am I missing that prevents mod from being constructed with proto as it's prototype?
Here is a fiddle with the above code.
Thanks heaps!!
modfunction is a factory that returns an object. It should not be, it should be a constructor (or method) that initialises properties onthis.new mod("Other message 1")?constructorWrapperorconstructorwould not have returned an object.