Reputation: 1501
I'm developing a "framework" and find myself at writing modules.
for each module exists a set of common initialization rules and common set of functions.
STEP 1. constructor function:
var ns = "namespace1";
t.scenarios[ns] = function (container, instanceName, options) {
// common for all scenarios, e.g. options initialization
t.core.defaultScenarioConstructor(this, ns, container, instanceName, options)
// things only for NAMESPACE1
this.PROPERTY1 = 1;
}
STEP 2. (question related) then I have a prototype
var p = t.scenarios[ns].prototype;
p.newfunction = function(){
this.PROPERTY1; // accessible
}
which gets filled with THINGS_ONLY_FOR_NAMESPACE1
t.core.defaultScenarioPrototype(p);
STEP 3 / 4. instantiate class (with new keyword) & call dom builder
p.initNewView = function(container) {/* build dom and assign handlers*/}
Now the question... I would like to do common constructor/prototype initialization within the other "core" module. If on STEP 2 we add functions to prototype then they have "this" keyword and can access CURRENT_INTANCE fields, e.g. PROPERTY1.
If however the prototype is passed as a variable to "defaultScenarioPrototype" builder, then all functions have the other "this" of CORE class, where lives the builder.
How should we add "common" functions to a prototype from another module?
Upvotes: 0
Views: 88
Reputation: 39260
As requested I'll add my comment as an answer. To call a function within a certain this
context you can use Function.prototype.call, Function.prototype.apply or Function.prototype.bind.
Bind is used a lot in cases where you pass a callback and don't want to use closures:
setTimeout(myOjbect.somefunction,100);//this in somefunction is window
setTimeout(function(){
myObject.somefunction();
},100);//this in somefunction is myObject but a closure is created
setTimeout(myObject.somefunction.bind(myObject),100);//this is myObject
//and no closure is created
One would assume that bind uses less memory and is faster but I recently read somewhere that bind is actually slower than passing a closure so I'm not sure about the memory consumption either.
Upvotes: 1