The two concepts of value-copy exist in the process of variable assignment and parameter transfer. In JavaScript, variable assignment and parameter transfer are syntactically indistinguishable, and are completely judged by the type of the value.

let a = 100;
let b = a;
b++;
console.log(a, b); / / 100 101

let obj = { name: 123 };
let obj1 = obj;
obj1.name = 'obj1 name';
console.log(obj); // { name: 'obj1 name' }
Copy the code

According to the data type, it can be divided into two types. One is simple value, which can also be called direct value (string, number, Boolean, symbol, undefined, null). The second type is complex values (objects, which contain array functions).

Simple values always carry out variable assignment and parameter transfer through value copy. Complex values are always assigned and passed by reference copy.

Because of this mechanism, there are a lot of cases where we accidentally write code that doesn’t meet our expectations. But once we understand this, we realize that we “opened it” the wrong way.

Correct way to open:

  • Deconstructing assignments avoids reference copying
const obj = {name: 'obj'};
let { name } = obj;
name = 'other name'; // Declare a new variable name and assign the initial value to 'obj'.An array of slice ()const arr = [1.2.3];
const other = arr.slice(); // Slice () returns a reference to a shallow copy of an array
other.push(4);
console.log(arr, other); // [1, 2, 3] [1, 2, 3, 4]
Copy the code

JavaScript reference copying is actually a very popular design to reduce heap memory consumption.

Sometimes we can do interesting things with reference copying.

Suppose you have a function popover component whose return value is a function reference that destroys the popover.

export interface IConfig {
  content: Node;
}
const fnModal = (config: IConfig): () = > void= > {
  
  // Create popover,
  
  // Returns the delete event
  return function remove() {
    // delete Modal}}Copy the code

Now suppose there is a button in the content, and clicking the button closes the popover. What do you do at this point? The result of calling fnModal function is to delete the function reference of popover, and the content binding click event in content needs to be realized through function call. So theoretically we can’t get a reference to the function that destroys the popover. But you can do this with reference assignment.

const obj = {
  removeHandler: null}; obj.removeHandler = fnModal({content: (<div> <button onclick={obj.removehandler}>delete</button </div>)});Copy the code

We use an object to do this, so that the processing ensures that the reference to the closed function is retrieved at the time the function returns. The click event is theoretically always executed later than the return time of the function result. Make sure the logic is correct.