0

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.

adrianton3
  • 2,258
  • 3
  • 20
  • 33
  • [Singleton pattern in JavaScript](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Evan Davis Feb 15 '13 at 20:13
  • You could do `Function.prototype.g = function() { /* code2 */ };` but then all functions would have g's functionality, even g itself. I'm not sure what you're trying to achieve here at all. Could you provide some usecase for this? – YingYang Feb 15 '13 at 20:36

2 Answers2

3
var F = {
    f: function() {
        /* code1 */
    },
    g: function() {
        /* code2 */
    }
 };

F.f = function() { /* redefine F.f() */ }
// or
delete F.f;

F.g(); // still works

-

Updated answer from question clarification

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 */
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
0

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

Kaeros
  • 1,138
  • 7
  • 7
  • This will log "Something.." as soon as the file is executed and then there is no way to call g...??? not sure what you're trying to accomplish here. – jondavidjohn Feb 15 '13 at 20:24