Primitive value vs Reference value

前端 未结 7 1575
执念已碎
执念已碎 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:39

    Primitive versus reference:

    Variable are segments of memory (RAM) which the javascript engine reserves to hold your data. Within these variables can be stored 2 kinds of values:

    • Actual data: For example a string or number. This means that the actual memory (i.e. the bytes in memory) hold the data itself.
    • References to objects: For example Array objects or Function objects. This means that this variable just holds a reference to another location in memory where this object resides.

    Difference between primitive and reference value:

    When a primitive value gets assigned to a variable the data (values of the bits) just copied. For example:

    Primitive values:

    let num1 = 10;
    
    // What happens here is that the bits which are stored in the memory container 
    // (i.e. variable num1) are literally copied into memory container num2
    let num2 = num1;

    Reference values:

    let objRef1 = {prop1: 1}
    
    // we are storing the reference of the object which is stored in objRef1
    // into objRef2. Now they are pointing to the same object
    let objRef2 = objRef1;
    
    // We are manipulating the object prop1 property via the refernce which
    // is stored in the variable objRef2
    objRef2.prop1 = 2;
    
    // The object which objRef1 was pointing to was mutated in the previous action
    console.log(objRef1);

提交回复
热议问题