Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling member methods before object declaration is finished [duplicate]

Sometime ago I heard that it was good practice to wrap your code in a big object to serve as a namespace in order to reduce global namespace cluttering and to facilitate library export, so I tried this.

var wrapper = {
    foo: function(){
        return 42;
    },
    bar: this.foo()
};

It fails, claiming that "foo is not defined". Calling methods before finishing the object declaration is probably bad, so I moved bar, and it worked.

var wrapper = {
    foo: function(){
        return 42;
    },
};
wrapper.bar = wrapper.foo();

I feel that this can become kind of ugly, especially with nested namespaces and such, so are there any workarounds that don't make it hard to see all of the wrapper's members at once?

like image 765
Name Here Avatar asked Nov 12 '22 23:11

Name Here


1 Answers

The problem is that this is going to equal the global context. You need to access the function like so:

var wrapper = {
    foo: function(){
        return 42;
    },
    bar: null,
    init : function() {
       // all initialization code goes here
       wrapper.bar = wrapper.foo();
    }
};

wrapper.init();

This method is great for organizing your code into logical chunks so you and future developers can easily find what you are looking for in your javascript.

like image 180
Jonathan Crowe Avatar answered Nov 14 '22 22:11

Jonathan Crowe