JavaScript objects as function parameters

China☆狼群 提交于 2019-12-11 12:49:53

问题


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);

回答1:


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.




回答2:


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!




回答3:


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'



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4934942/javascript-objects-as-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!