Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

Javascript Variable Scope. How Do I Access an Object Var From an Internal Object Function?

I'm wondering how to access the "nam"e variable with a function in a javascript object like so:

function myObj() {
    this.vars = {
        name: 'bob',
        age: '42'
    }
    this.functions = {
        sayName: function() {
            alert(this.vars.name);
        }
    }
}

var obj = new myObj();
obj.functions.sayName();

What am I missing here?

I can get the name var if I pass a reference to itself like:

function myObj() {
    this.vars = {
        name: 'bob',
        age: '42'
    }
    this.functions = {
        sayName: function(name) {
            alert(name);
        }
    }
}

var obj = new myObj();
obj.functions.sayName(obj.vars.name);

but that seems a little redundant... thoughts?

Upvotes: 2

Views: 2935

Answers (3)

gdoron
gdoron

Reputation: 150253

Just remove this:

function myObj() {
    var vars = {
        name: 'bob',
        age: '42'
    };
    this.functions = {
        sayName: function() {
            alert(vars.name);
        }
    };
};

var obj = new myObj();
obj.functions.sayName();​

LIVE DEMO

Upvotes: 1

Reid
Reid

Reputation: 19409

The issue is that in your function this.functions.sayName, the this keyword refers to this.functions instead of the current object1.

Here is a fix for that issue:

function myObj() {
    var vars = this.vars = {
        name: 'bob',
        age: '42'
    }
    this.functions = {
        sayName: function() {
            alert(vars.name);
        }
    }
}

var obj = new myObj();
obj.functions.sayName();

This creates a local variable inside of myObj that you can access from any inner scope. It also exposes that variable to the outside world as a property of any instantiated myObj class, which means you can still do something like

obj.vars.name = 'test';

and it will still change the internal state of the object. That's probably the best solution for your current setup.

1 The behavior of the this keyword in JavaScript is interesting. I recommend the excellent writeup at the Mozilla Developer Network.

Upvotes: 5

McGarnagle
McGarnagle

Reputation: 102743

You could do it like this:

var thisObj = this;
this.functions = {
    sayName: function() {
        alert(thisObj.vars.name);
    }
}

Not sure if that's the best solution, but it works. The Javascript this always refers to the internal scope if you're inside a function.

Upvotes: 1

Related Questions