3

I am trying to write some javascript functions for a web application.

Following the advice from here: How do I declare a namespace in JavaScript?

I am trying to make the code unobtrusive by wrapping everything in named functions, however I am running into difficulty accessing properties in the parent function when inside a child anonymous function.

For example:

var title_picker = new function(){
    // This property should be public
    this.callback=function(){};


    var ok=function(){
        var title = $('input#title').val();
        callback(title) // <--- 
    }
...

When inside the "ok" function, what is the best way to reference the "callback" property?

Community
  • 1
  • 1
Chris
  • 6,076
  • 11
  • 48
  • 62

2 Answers2

4

With the code as written, no there isn't.

You can access variables from the scope of the parent, unless they are overwritten in the narrower scope.

this is always overwritten.

You can copy this to another variable that remains in scope though:

var title_picker = new function(){

    var self = this; // Copy this to a variable that stays in scope

    // This property should be public
    this.callback = function(){};


    var ok=function(){
        var title = $('input#title').val();
        self.callback(title) // self is still in scope
    }
...
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks, that looks like it will do the trick nicely. Out of interest why the aversion to the new keyword. My understanding is a big vague over what the new keyword does in general. In this case it seems to run the function and returns its "this" scope, which is what I want in this case. (To be able to for example trigger title_picker.show() from elsewhere in my code). – Chris Nov 07 '11 at 17:13
  • @Chris — You're using a function expression. You use `new` when you call a function you defined earlier that you are going to use like a class … and argh. No, I think you need `this` there. I've just never seen anyone use a function *expression* like that. – Quentin Nov 07 '11 at 17:16
2

Perhaps something like this:

var title_picker = new function(){
    // This property should be public
    this.callback=function(){};
    var that = this;


    var ok=function(){
        var title = $('input#title').val();
        that.callback(title) // <--- 
    }
...

Though there are many frameworks that do this kind of thing for you (yui, dojo, prototype...)

Lucas
  • 14,227
  • 9
  • 74
  • 124