Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Using JavaScript, say I have a function X, and in that function an object called objectX is created. function X returns objectX. Later in the code function Z(somevar, anObject) receives objectX as one of it's parameters.

Now in function Z, is objectX and all its properties referred to as anObject inside function Z?

And what happens if function Z returns anObject? Will the rest of the code see the object as "objectX" or "anObject"?

function X() {
    ...
    objectX = {};
    ...
    return objectX;
}

X();

function Z(anything, anObject) {
    ...
    return anObject
}

Z(something, objectX);
share|improve this question
You really need to explain what you're talking about better. Use psudo code or something. The way you have it described, function X never gets called. – Incognito Feb 8 '11 at 15:34
@user257493 - code added. – Ben Feb 8 '11 at 15:44
That code doesn’t run. The X function is never called: Javascript is case-sensitive, so x()' is something different than X()`... – Martijn Feb 8 '11 at 16:01
@ Martijn - sorry that's a typeo. I fixed. – Ben Feb 8 '11 at 16:03

5 Answers

up vote 0 down vote accepted

Javascript has function scope. This means that every variable declared within a function, will only be accessible from within that function.

If you’d properly declared the objectX variable with var, as follows:

function X() {
    ...
    var objectX = {};
    ...
    return objectX;
}

then objectX would only be known as objectX inside the X function. Elsewhere, it would be known as whatever variable you’d assigned it to. Since in your code, you don’t assign the result of X() to anything, objectX would not be accessible from anywhere.

However, here’s one of Javascript’s more serious design flaws: if you don’t explicitly declare a variable (using the var statement, or as a function parameter), that variable will automatically become a global variable. That means that it will be accessible anywhere.

Because of this, in your code above, you can access objectX everywhere by that name.

anObject, on the other hand, is properly declared (as a parameter), and that means its scope will be limited to the Z function.

In short, the way your code is written, objectX is accessible everywhere by way of the objectX variable, and inside the function Z, you can reference it both as objectX and as anObject.


Do note, however, that global variables are a Bad Thing™, since they can make it quite hard to figure out what variable gets assigned by who, when, and why — as you’ve noticed.
While Javascript makes it impossible to completely avoid them, as a rule you should try to keep the scope of your variables as small as possible (scope = where in your program that variable can be accessed).

To that end, I would recommend refactoring your code like igorw has.

share|improve this answer

anObject and objectX both are referencing to the same space in memory, so, name it as you want, it's always the same object.

Good luck!

share|improve this answer
@ Gonzalo - Even when function Z returns the object as "anObject", I can still refer to it as objectX? – Ben Feb 8 '11 at 15:33
+1 for "referencing to the same space in memory" – kjy112 Feb 8 '11 at 15:54

This is mostly a question of scope.

function X() {
    // local objectX, only accessible through this name inside X()
    var objectX = {};
    objectX.foo = 'bar';
    return objectX;
}

function Z(somevar, anObject) {
    // anObject is passed in as a parameter
    // it's only accessible through this name inside Z()
    anObject.foo = somevar;
    return anObject;
}

// get the 'objectX' from X() and store it in global variable a
var a = X();

// pass the received 'objectX' into Z()
// note that the variable names objectX and anObject cannot be accessed
// because they are local variables of the functions X() / Z()
var b = Z('baz', a);

// a is now the same as b, they both reference the same var
// a.foo and b.foo both are set to 'baz'
share|improve this answer
@ igorw - I don't think you're right about the scope. when you return objectX, it is indeed accessible outside of the function as 'anObject'. I'm already doing that in the program I'm writing. I just got to a situation in my coding that I may need to pass objectX into function Z – Ben Feb 8 '11 at 15:48
2  
@Ben Then you're probably doing it wrong. If you don't use the var keyword, the var becomes global (this is bad) and will be accessible from everywhere. – igorw Feb 8 '11 at 15:51
I see what you mean. Thanks. – Ben Feb 8 '11 at 15:53
+1 "for var becomes global without using var" – kjy112 Feb 8 '11 at 15:59

I believe an example is the best way to teach. Here is some code (click here to see it in JS Bin):

// Defines the variable to keep track of how many objects X() defines.
var num = 1;

// Instantiate another variable to see if it is changed by Z().
var anObject;

// Creates an object with a comment and a random number.
function X() {
  // Create an object and give it a name.
  var objectX = {comment : "Creation #" + num};
  // Increase the value of num.
  num++;
  // Add another random number between 0 and 100 inclusively.
  objectX.randNum = Math.round(Math.random() * 100);
  // Return objectX.
  return objectX;
}

// Modifies the second parameter by adding the value of the first parameter.
function Z(somevar, anObject) {
  anObject.somevar = somevar;
  return anObject;
}

var objectX = X(), objectY = X();
objectX2 = Z('coolness', objectX);

// Notice that objectX is still the result of calling X() the first time.
alert("objectX.comment = " + objectX.comment);

// Notice that objectX is not equal to objectY.
alert("objectX === objectY evaluates to " + (objectX === objectY));

// Notice that objectX2 is the same thing as objectX.
alert("objectX === objectX2 evaulates to " + (objectX === objectX2));

// Notice that anObject is not defined.
alert("typeof anObject evaluates to " + (typeof anObject) + " after Z is called.");​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

alert("Now review the JavaScript code.");

If read through the comments, you will find the answers to your questions. First you will notice that in function Z, since I passed objectX as the second parameter, inside of the function, it could be referred to by anObject. Second you will notice that once outside of function Z, anObject no longer refers to objectX. The comments also reveal other things that are true in JavaScript.

share|improve this answer
I think I'm way in over my head. – Ben Feb 8 '11 at 16:23

Here is link to jsfiddle

Lets take the following example below:

Person = function(name){
 this.name = name;
}

function x(){
     var john = new Person('john');
     return john;
}

function z(tempVar, anObject){
    var newObj = anObject;
    newObj.name = tempVar;
    return newObj;
}

myPerson = x();
console.log(myPerson.name); //john
console.log(z('peter', myPerson).name);  //peter
console.log(myPerson.name); //peter

You can see, even though you created a new object in z but because they are referencing to the same object myPerson's name property is also changed after z() is called.

share|improve this answer
do you wish to access the object created in function x? – kjy112 Feb 8 '11 at 15:51
Yes. I see what you're saying now. Thanks. – Ben Feb 8 '11 at 15:52
@Ben if you take a look at @Clarence Fredericks example it brings in how JavaScript uses the 'new' and that furthers this topics on how JavaScript uses Objects to do OOP etc...very good stuff – kjy112 Feb 8 '11 at 16:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.