Is JavaScript a language that uses pass-by-reference or pass-by-value?
P粉002546490
P粉002546490 2023-10-11 17:50:30
0
1
624

Primitive types (numbers, strings, etc.) are passed by value, but objects are unknown because they can all be passed by value (in this case, we think that the variable holding the object is actually a pair of objects reference) and pass-by-reference (when we think of an object's variables as holding the object itself).

Although it doesn't matter in the end, I would like to know what is the correct way to present the parameter passing convention. Is there an excerpt from the JavaScript specification that defines the semantics related to this?

P粉002546490
P粉002546490

reply all (1)
P粉195402292

JavaScript is fun. Consider this example:

function changeStuff(a, b, c) { a = a * 10; b.item = "changed"; c = {item: "changed"}; } var num = 10; var obj1 = {item: "unchanged"}; var obj2 = {item: "unchanged"}; changeStuff(num, obj1, obj2); console.log(num); console.log(obj1.item); console.log(obj2.item);

This produces the output:

10 changed unchanged
  • Ifobj1is not a reference at all, changingobj1.itemwill not have any effect onobj1outside the function.
  • If the parameters are correct references, then everything changes.numwill be100, andobj2.itemwill read"changed". Instead,numremains10andobj2.itemremains"unchanged".

Instead, the situation is that the incoming item is passed by value. But an item passed by value is itself a reference. Technically, this is called ashared call.

In practical terms, this means that if you change the parameters themselves (such asnumandobj2), it will not affect the input to the scope. However, if you change theinnerof the parameter, it will propagate upward (same asobj1).

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!