2

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

awesome answer. I do indeed need to keep the variables accessible to outside components so adding the this.vars = is key. Thanks!
1

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.

Comments

1

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

2 Comments

That creates an implicit global and decouples the vars object from any specific object. If you instantiate another myObj, you end up having multiple objects share state.
@Reid. I had a small mistake, take a look on the updated fiddle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.