简体   繁体   English

Javascript:通过引用传递

[英]Javascript: Pass By Reference

Someone can explain me in the following code, why when I do o = {}, the object is not being reset? 有人可以在下面的代码中解释我,为什么当我做o = {}时,对象没有被重置?

var funky = function (o) {
    o.z = null;
    o.a = "aaa";        
    o = {};
};

var x = { z: "zzz"};
funky(x);

console.log(x);

Because JavaScript doesn't pass by reference. 因为JavaScript没有通过引用传递。 It passes references by value. 它按值传递引用。

The difference is subtle, but important. 差异很微妙,但很重要。 The gist of it is, the value of an object variable isn't an object; 它的要点是,对象变量的值不是对象; it is a reference to an object. 它是对象的引用 Passing a variable passes a copy of that reference. 传递变量会传递该引用的副本。 With it you can modify the content of the object virtually at will, but you couldn't replace it with a whole other object in a way the caller could see. 有了它,您可以随意修改对象的内容,但不能以调用者可以看到的方式将其替换为整个其他对象。

o is just an alias to whatever it's currently pointing, it's not the instance (pass by value). o只是它当前指向的任何别名,它不是实例(按值传递)。

If you want to emulate "pass by reference", you can do it: 如果你想模仿“按引用传递”,你可以这样做:

var x = { ... };
var container = { x: x };
funky(container);

Now you can reset it in funky() : 现在你可以在funky()重置它:

container.x = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM