JavaScript 对象作为函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4934942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:24:30  来源:igfitidea点击:

JavaScript objects as function parameters

javascriptobjectparameter-passing

提问by Ben

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.

使用 JavaScript,假设我有一个函数 X,在该函数中创建了一个名为 objectX 的对象。函数 X 返回 objectX。稍后在代码函数 Z(somevar, anObject) 中接收 objectX 作为它的参数之一。

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

现在在函数 Z 中,objectX 及其所有属性是否在函数 Z 中被称为 anObject?

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

如果函数 Z 返回一个对象会发生什么?其余的代码会将对象视为“objectX”还是“anObject”?

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

X();

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

Z(something, objectX);

回答by Gonzalo Larralde

anObjectand objectXboth are referencing to the same space in memory, so, name it as you want, it's always the same object.

anObject并且objectX两者都引用内存中的相同空间,因此,根据需要命名它,它始终是同一个对象。

Good luck!

祝你好运!

回答by igorw

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'

回答by Clarence Fredericks

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

我相信一个例子是最好的教学方式。这是一些代码(单击此处在 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.

如果通读评论,您将找到问题的答案。首先你会注意到在函数 Z 中,由于我将 objectX 作为第二个参数传递给函数内部,它可以被 anObject 引用。其次,您会注意到一旦在函数 Z 之外,anObject 不再引用 objectX。注释还揭示了 JavaScript 中的其他真实情况。

回答by Martijn

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

Javascript 有函数作用域。这意味着在函数内声明的每个变量都只能从该函数内访问。

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

如果您使用 正确声明了 objectX 变量var,如下所示:

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

then objectXwould only be known as objectXinside the Xfunction. 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, objectXwould not be accessible from anywhere.

thenobjectX只会objectXX函数内部被称为。在其他地方,它将被称为您分配给它的任何变量。由于在您的代码中,您没有将结果分配X()给任何东西,objectX因此无法从任何地方访问。

However, here's one of Javascript's more serious design flaws: if you don'texplicitly declare a variable (using the varstatement, or as a function parameter), that variable will automatically become a globalvariable. That means that it will be accessible anywhere.

但是,这里有一个 Javascript 更严重的设计缺陷之一:如果您没有显式声明变量(使用var语句,或作为函数参数),该变量将自动成为全局变量。这意味着它可以在任何地方访问。

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

因此,在上面的代码中,您可以objectX通过该名称访问任何地方。

anObject, on the other hand, isproperly declared (as a parameter), and that means its scope will be limited to the Zfunction.

anObject,另一方面,正确声明(作为参数),这意味着它的范围将被限制在Z函数内。

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

简而言之,您的代码编写objectX方式可以通过objectX变量在任何地方访问,并且在函数内部Z,您可以将其引用为 asobjectX和 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).

但是,请注意,全局变量是坏事吗?,因为它们会让您很难弄清楚由谁、何时以及为什么分配了哪些变量——正如您所注意到的。
虽然 Javascript 无法完全避免它们,但作为一项规则,您应该尽量保持变量的范围尽可能小(范围 = 在程序中可以访问该变量的位置)。

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

为此,我建议像igorw一样重构您的代码。

回答by u476945

Here is link to jsfiddle

这是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.

您可以看到,即使您在 z 中创建了一个新对象,但由于它们引用了同一个对象,因此在调用 z() 后,myPerson 的 name 属性也发生了更改。