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?
The issue is that in your function
this.functions.sayName, thethiskeyword refers tothis.functionsinstead of the current object1.Here is a fix for that issue:
This creates a local variable inside of
myObjthat you can access from any inner scope. It also exposes that variable to the outside world as a property of any instantiatedmyObjclass, which means you can still do something likeand 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
thiskeyword in JavaScript is interesting. I recommend the excellent writeup at the Mozilla Developer Network.