Reputation: 2358
Can this be rewritten in some better form?
function F() { return F.f(); } //wrapping :(
F.f = function() { /* code1 */ }
F.g = function() { /* code2 */ }
F.f = some_other_function
F.g() //this still works :D
I'm never going to create any instances of F. I just use it as a sort of a namespace.
I've tried doing the following but F.g doesn't get preserved (I can understand why, but I'd like a nice workaround to be able to change the code and behaviour of F but not the bindings like F.g):
function F() { /* code1 */ } //no wrapping :D, no need for F.f
F.g = function() { /* code2 */ }
F = some_other_function
F.g() //this points to nowhere now :(
EDIT:
I want to not have to use F.f anymore as a wrapper for code1
.
EDIT2: The first piece of code is valid JS and has the behaviour that I want. The problem is that I don't like that I have to use F.f at all. I would like to do it like in the second but of code and still have F.g working.
At some point at runtime I would like to change code1
and leave everything else untouched.
Upvotes: 0
Views: 105
Reputation: 62392
var F = {
f: function() {
/* code1 */
},
g: function() {
/* code2 */
}
};
F.f = function() { /* redefine F.f() */ }
// or
delete F.f;
F.g(); // still works
-
This is a way to accomplish this, although this whole idea is a bit off. Not sure why you would want this pattern.
function generate() {
var f = function() {
/* code1 */
};
var ret_val = function() {
f();
};
ret_val.g = function() {
/* code2 */
};
ret_val.setBehaviour = function(new_func) {
f = new_func;
};
}
F = generate();
F(); /* code1 */
F.g(); /* code2 */
F.setBehaviour(function() { /* redefine F() */ });
F.g(); /* code2 still works */
F(); /* new behaviour */
Upvotes: 3
Reputation: 1138
What about:
var F = (function() {
console.log("Something..");
return function() {
function g() {
console.log("I'm G!");
}
};
})();
F.g();
Now you can initialize something (looks like that's you want with F.f) and preserve F.g
Upvotes: 0