Chris
Chris

Reputation: 6246

How to access public property of parent function in javascript?

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?

Upvotes: 3

Views: 1746

Answers (2)

Quentin
Quentin

Reputation: 944171

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
    }
...

Upvotes: 4

Lucas
Lucas

Reputation: 14969

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...)

Upvotes: 2

Related Questions