Functions in js copied / passed by value or reference

I know that objects in Javascript are copied / passed by reference. But what about functions?

I tried this code when I jumped on something confusing. Here is the code snippet:

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

y = x;

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

y; // Prints function() { console.log('hey 1'); }
Run codeHide result

If functions like objects are copied / passed by reference, why is y not updated to print "hey 2"?

If this behavior is due to the fact that “x” is assigned by a new function, is there a way for the variable “y” for a newly assigned function when x changes?

+4
source share
3 answers

Everything in JS is passed by value , where the value for objects and functions is a reference.

, , - , ( - ):

, :

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

x function() that logs 1 ( )

y = x;

y function() that logs 1 ( )

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

x function() that logs 2 ( ), y

y;

y function() that logs 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'
+5

, , / , y "hey 2"?

. pass-by-value JavaScript. , , pass-by-reference.

, , :

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

/ , , .

, "x" , "y" x?

. y.

+1

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

0
source

Source: https://habr.com/ru/post/1616589/


All Articles