I'm looking for some good comprehensive reading material on when Javascript passes something by value and when by reference and when modifying a passed item affects the value outside a function and when not.(我正在寻找一些有关Javascript何时按值传递值,何时按引用传递以及何时修改传递的项目影响函数外部值以及何时不传递值的良好综合阅读材料。)
I'm also interested in when assigning to another variable is by reference vs. by value and whether that follows any different rules than passing as a function parameter.(我还对何时通过引用还是按值分配给另一个变量以及是否遵循除传递为函数参数之外的任何其他规则感兴趣。)I've done a lot of searching and find lots of specific examples (many of them here on SO) from which I can start to piece together pieces of the real rules, but I haven't yet found a single, well written document that describes it all.(我已经进行了很多搜索,找到了很多具体的示例(其中很多都在SO上),可以从这些示例中整理出一些真实的规则,但是我还没有找到一个写得很好的文档来描述这一切。)
Also, are there ways in the language to control whether something is passed by reference or by value?(另外,该语言中是否有方法可以控制是通过引用还是通过值传递某些东西?)
Here are some of the types of questions I want to understand.(以下是一些我想了解的问题。)
These are just examples - I'm actually looking to understand the rules the language goes by, not just the answers to specific examples.(这些只是示例-我实际上是在寻求理解语言所遵循的规则,而不仅仅是特定示例的答案。) But, here are some examples:(但是,这里有一些例子:)function f(a,b,c) {
a = 3;
b.push("foo");
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
When are the contents of x, y and z changed outside the scope of f for all the different types?(对于所有不同类型,何时x,y和z的内容在f的范围之外更改?)
function f() {
var a = ["1", "2", "3"];
var b = a[1];
a[1] = "4";
// what is the value of b now for all possible data types that the array in "a" might hold?
}
function f() {
var a = [{yellow: "blue"}, {red: "cyan"}, {green: "magenta"}];
var b = a[1];
a[1].red = "tan";
// what is the value of b now and why?
b.red = "black";
// did the value of a[1].red change when I assigned to b.red?
}
If I want to make a fully independent copy of an object (no references whatsoever), what's the best practice way to do that?(如果我想制作一个对象的完全独立的副本(什么都没有引用),那么这样做的最佳实践方法是什么?)
ask by jfriend00 translate from so