Primitive value vs Reference value

前端 未结 7 1572
执念已碎
执念已碎 2020-11-22 08:23

I read a book called \"Professional Javascript for web developer\" and it says: \"Variable is assigned by Reference value or Primitive Value. Reference values are objects st

相关标签:
7条回答
  • 2020-11-22 08:51

    A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit. The number type is the largest of the primitive types. If each JavaScript variable reserves eight bytes of memory, the variable can directly hold any primitive value.

    This is an oversimplification and is not intended as a description of an actual JavaScript implementation.

    Reference types are another matter, however. Objects, for example, can be of any length -- they do not have a fixed size. The same is true of arrays: an array can have any number of elements. Similarly, a function can contain any amount of JavaScript code. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value. Typically, this reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.

    The distinction between primitive and reference types is an important one, as they behave differently. Consider the following code that uses numbers (a primitive type):

    var a = 3.14;  // Declare and initialize a variable
    var b = a;     // Copy the variable's value to a new variable
    a = 4;         // Modify the value of the original variable
    alert(b)       // Displays 3.14; the copy has not changed
    

    There is nothing surprising about this code. Now consider what happens if we change the code slightly so that it uses arrays (a reference type) instead of numbers:

    var a = [1,2,3];  // Initialize a variable to refer to an array
    var b = a;        // Copy that reference into a new variable
    a[0] = 99;        // Modify the array using the original reference
    alert(b);         // Display the changed array [99,2,3] using the new reference
    

    If this result does not seem surprising to you, you're already well familiar with the distinction between primitive and reference types. If it does seem surprising, take a closer look at the second line. Note that it is the reference to the array value, not the array itself, that is being assigned in this statement. After that second line of code, we still have only one array object; we just happen to have two references to it.

    0 讨论(0)
提交回复
热议问题