I have an instance function in javascript and for naming conventions I have other instance function added as property of the first instance function object. It’s better illustrated in the following working JavaScript.
var MyModule = (function() { // instance function
return function() {
console.log("ran MyModule");
}
}());
MyModule.RelatedModule = (function() { //second instance function is a property of first instance function object
return function() {
console.log("ran RelatedModule");
}
}())
var inst1 = new MyModule(), // logs "ran MyModule"
inst2 = new MyModule.RelatedModule(); // logs "ran RelatedModule"
This works as intended with no errors. What I’d like to do though is to create the function definition for MyModule after I’ve created the MyModule object, can anyone help me achieve this? I’ve illustrated my attempts below.
var MyModule = {}; // create object first, try to set a constructor on it later
MyModule.RelatedModule = (function() { // add properties to the MyModule object
return function() {
console.log("ran RelatedModule");
}
}())
// the following does not work, I'd like to set the `MyModule` constructor instance function and retain the `MyModule.RelatedModule` property
MyModule.constructor = (function() {
return function() {
console.log("ran MyModule");
}
}());
So, how do I retain the properties of an object and change it’s constructor?
You’re confusing a couple of concepts. In your first example,
MyModuledoesn’t have a constructor, it is a constructor. That is, it’s a function object that you intend to use with thenewoperator to create new objects. Those objects will have aconstructorproperty that points back toMyModule(the function that created them). Changing thisconstructorproperty won’t have any effect onMyModule; that property is just a pointer back to the function that instantiated the object.In other words, you can’t change
MyModule‘s constructor. That’s a meaningless statement.Now, when you write:
…you create a new object whose
constructorproperty isObject():Again, changing this property doesn’t really do much (except obfuscate some useful book-keeping).
At this point
MyModuleis just a plain-old object. It’s not a function at all. That’s why you’re getting the “not a function” error. Because it’s not, but you’re trying to use it as though it is. If you want that name to refer to a function (i.e. to a different object) then you’re going to lose all references to any properties you previously set, because you’re pointing at an entirely new object.That’s just the way it is.
Now, you could save a reference to the object that contains all those previously-set properties and copy them back into
MyObjectonce you’ve pointed that name at a function. But I’m not sure what the point would be.