Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  180] [ 2]  / answers: 1 / hits: 20562  / 12 Years ago, mon, july 2, 2012, 12:00:00

So I encountered a problem. I have this object called myTree. And that object has properties. One of the properties contains a method like this:



prep: function (variable) {
/* some code */
}


In that method there is an array myarray and I want to know, whether it is possible to access the content of that array, and if it is, how I would do that.



I've made a demo on jsFiddle, and in the end of the JavaScript window you can see that I'm alerting the object prep in which myarray is contained.



http://jsfiddle.net/Wp7Xh/1/


More From » object

 Answers
97

JavaScript variables are function-scoped. It is not possible to access variables belonging to an inner scope (i.e. function) from an outer scope.



If you want that kind of access, you must make the respective variable part of the outer scope.



var myTree = function() {
var myarray = [];

this.prep = function (variable) {
myarray.push(variable);
};
}


In your scenario, where you have nested objects, it's quite similar:



var myTree = {
myarray: [],
prep: function (variable) {
this.myarray.push(variable);
}
}


The only difference is the use of the this keyword.



When you define an object via the object literal syntax (obj = {prop: value}) instead of via a constructor (function Obj(value) { this.prop = value; }; obj = new Obj(value);), then all defined properties will be public by default.



When you call a function on that object, this will point to the respective object instance.



Accessing an inner scope variable from outside is still impossible. There's no way around that.



Generally speaking: You can access properties of the objects you construct. You can never access function local variables (except from the inside of nested functions).


[#84527] Saturday, June 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimr

Total Points: 468
Total Questions: 99
Total Answers: 93

Location: Serbia
Member since Sun, Jul 11, 2021
3 Years ago
;