Why would you add members to a constructor function and not the prototype?
function foo() {
}
foo.prototype.isThereSayShoeSize = function() {
console.log(this.sayShoeSize);
}
foo.fooObject = {num: 100, shoeSize: 43}
foo.sayShoeSize = function() {
console.log(foo.fooObject.shoeSize)
}
var myFoo = new foo();
console.log(myFoo.sayShoeSize); //undefined
myFoo.isThereSayShoeSize() //undefined
The members are not owned by instances nor shared amongst instances. So these members can not be accessed through an instance.member syntax nor with the this keyword within an instance.
So it would seem that members added to the constructor function have no relation to the type.
I can think of only two possible explainations. 1 to conserve namespace space by grouping these memebers with the type, which doesn’t make a lot of sense if they aren’t related to the type. 2 They are static members which can be accessed without an instance of the type. This makes sense if there are objects of another type that wish to consume these members. But in the context which I have seen this pattern these members are only used by instances of the type they are attached to. So in that context they are relevant to the type and only consumed by instances of the type, so why not put them in the prototype?
I am a little confused by this as you can probably tell. I think perhaps this pattern of adding members to the constructor is just inappropriate in the context I have seen it, and the members should have been added to the prototype. But would you call these members static? And would having members that are consumable by both the type they are attached to and other types be the main use for this pattern?
When you do this:
it is similar to setting a class variable in the C++ world that is available to all instances as
foo.fooObjectand the same for all instances. It’s a namespaced way of setting global variables. As you point out they are not instance variables, so this technique should only be used when a scoped global variable is the desired outcome.