Javascript js中的函数按值或引用复制/传递

Javascript js中的函数按值或引用复制/传递,javascript,Javascript,我知道Javascript中的对象是通过引用复制/传递的。但是函数呢 我正在尝试这个代码,突然发现了一些令人困惑的问题。以下是代码片段: x=function(){console.log('hey 1');} y=x; x=function(){console.log('hey 2');} y、 //打印function(){console.log('hey 1');}x=function(){console.log('hey 2');}没有更改x变量中包含的对象,而是修改x变量的内容。JS中

我知道Javascript中的对象是通过引用复制/传递的。但是函数呢

我正在尝试这个代码,突然发现了一些令人困惑的问题。以下是代码片段:

x=function(){console.log('hey 1');}
y=x;
x=function(){console.log('hey 2');}

y、 //打印function(){console.log('hey 1');}
x=function(){console.log('hey 2');}
没有更改x变量中包含的对象,而是修改x变量的内容。

JS中的所有内容都是传递值,其中对象和函数的值是一个引用

这里发生的事情与对象发生的事情相同(因为函数只是:

下面是正在发生的事情的要点:

x = function() { console.log('hey 1'); }
x
指向记录1的
函数()(为该函数创建内存)

y
指向记录1的
函数()

x
现在指向一个新的
函数(),该函数记录2
(一个新的内存空间),但没有影响
y

y
仍然指向记录1的相同的
函数()


如果你想让对
x
的更改影响
y
,你应该做的是更改他们指向的东西,而不是更改他们指向的东西

例如:

var pointingAtMe = { log: function() { console.log('1'); } }
var x = pointingAtMe;
var y = pointingAtMe;

// change the actual thing x and y are both pointing to
x.log = function() { console.log('2'); } // this line also sets `y.log` and `pointingAtMe.log`since they all point to the same thing
// and the change gets applied to both
y.log(); // logs '2'
如果像对象这样的函数是通过引用复制/传递的,为什么y不更新为打印“hey 2”

你在做错误的假设。所有内容都是JavaScript。对象表示为引用是正确的,但这与

即使使用普通对象而不是函数,也看不到预期的结果:

var x = {foo: 42};
var y = x;
x = {foo: 21};
console.log(y.foo); // still 42

传递值/引用仅描述如何解析变量和参数,它与变量的值无关

如果这种行为是因为“x”被分配了一个全新的函数,那么当x发生变化时,变量“y”有没有办法分配给新分配的函数


不可以。如果不显式地指定给
y

,则此行为与执行
{x:1}
{x:2}
而不是
函数(){console.log('hey 1');}
函数(){console.log('hey 2');}
时所看到的行为相同。您当前的措辞听起来像是在观察对象与函数的不同模式,但事实并非如此。我在几乎所有编程语言中都发现了一个常量,
=
操作符只会修改它引用的变量(如实际引用“x”),而不会修改底层数据。如果一个类型有一个
.modify()
.add()
方法,这是底层数据可以更改的一种方式,以便通过多个变量可见。抱歉-自我警告:在JavaScript中,
=
用于修改对象的属性,其他引用肯定可以看到该属性。例如:
var b=a;a、 myprop=3;console.log(b.myprop)“如果像对象这样的函数是通过引用复制/传递的,为什么y不更新为打印‘hey 2’?”您做出了错误的假设。在JavaScript中,一切都是按值传递的。
y;
var pointingAtMe = { log: function() { console.log('1'); } }
var x = pointingAtMe;
var y = pointingAtMe;

// change the actual thing x and y are both pointing to
x.log = function() { console.log('2'); } // this line also sets `y.log` and `pointingAtMe.log`since they all point to the same thing
// and the change gets applied to both
y.log(); // logs '2'
var x = {foo: 42};
var y = x;
x = {foo: 21};
console.log(y.foo); // still 42