Raw and reference values

  • Raw values are the simplest data, and reference values are objects made up of multiple values

In JS, you cannot directly access the memory location, so you cannot directly manipulate the memory space of the object, so when you manipulate the object, you are actually manipulating the reference of the object. No attributes can be added to the original value (no error is reported after adding, but undefined is returned when accessing), and reference values can be dynamically added and deleted at any time.

Value of replication

  • In addition to being stored differently, the original and reference values are copied differently in variables
  • The original value

  • Reference value

Var a = a a = 2 console.log(b) //1 var obj = {a: Var obj2 = obj obj2.a = 2 obj2 = null console.log(obj) // {a: 2}Copy the code

Passing parameters

  • All functions in ECAMSript are passed by value. This means that values outside the function are copied to arguments inside the function. Similar value replication.
  • When a parameter is passed by value, the value is copied to a local variable. When passing parameters by reference. The location of a value in memory is stored in a local variable, which means that changes made inside the function affect variables outside.
Function add(item) {item += 1} let a = 2 add(a) console.log(a) //2 no changesCopy the code

This indicates that the original value is indeed passed as a function parameter.

  • Look at reference type pass-through
Let a = {name: 'zhangsan'} function add(obj) {obj.name = 'lisi'} console.log(a) // {name: 'lisi'} // changedCopy the code

In this example, it is found that the reference type is passed as if it were passed by reference. Because he’s changing the external values. but

let a = { name: 'zhangsan' } function add(obj) { obj = new Object() obj.name = 'lisi' } console.log(a) // {name: 'zhangsan'} // No changeCopy the code

This example proves that parameter passing in JS is indeed all value passing. When passing function parameters, the parameter = argument follows the js value copy rule.