The original value and the reference value in JS

Source: Internet
Author: User
Tags call by reference

In ECMAScript, a variable can have two types of values, the original value and the reference value.

Primitive Values -----simple data segments stored in stacks (stack), in other words, their values are stored directly in the variable access location;
The reference value -----The object stored in the heap (heap), that is, the value stored at the variable is a pointer (point) to the memory of the storage object.
If a value is a reference type, its storage space is allocated from the heap. Because the size of the reference value changes, it cannot be placed in the stack, otherwise
Will reduce the speed of variable lookups. Instead, the value placed in the stack space of the variable is the address that the object stores in the heap. The size of the address is fixed, so put it
Storage in the stack has no negative effect on the performance of the variable.
When we assign a variable to a variable, the parser first confirms whether the value is a base type value or a reference type value.
Common Basic data types:
    • Boolean. Boolean value, true and false .
    • Null. A special keyword that indicates a null value. JavaScript is case-sensitive and therefore null  Null NULL completely different from, or other variables.
    • Undefined. property when the variable is not defined.
    • Number. Represents a number, for example: 42 or3.14159。
    • String. Represents a string, for example: "Howdy"
    • Symbol (The newly added type in ECMAScript 6): A data type whose instance is unique and immutable.
The base data type is accessed by value, because the actual value stored in the variable can be manipulated directly. Example:

var a = 10;

var B = A;

b = 20;

Console.log (a); 10 Value

Above, B gets a worth copy, although the values of two variables are equal, but two variables hold two different base data type values.

  b Just a copy of a copy is saved. So, the change of B has no effect on a.

Reference type data: that is, the object type objects, such as: Object, Array, Function, data, and so on.

  The reference data type of JavaScript is the object that is stored in heap memory.

Unlike other languages, you can not directly access the location in the heap memory space and manipulate the heap memory space. Only the reference address of the object in the stack memory can be manipulated.

  Therefore, the reference type data is actually stored in the stack memory as the object's reference address in the heap memory. This reference address allows you to quickly find objects in the stored heap memory.

  var obj1 = new Object ();

var obj2 = obj1;

Obj2.name = "I have a name";

Console.log (Obj1.name); I have a name.

Describes the two reference data types pointing to the same heap memory object. Obj1 assigned to Onj2, actually this heap memory object in the stack memory of the reference address copied a copy to the OBJ2,

But in fact they point to the same heap of memory objects together. The actual change is the heap memory object.

basic Data Type He reference type data Difference

A different memory allocations when declaring variables:

1) Raw values: simple data segments stored in stacks (stack), that is, their values are stored directly in the location of the variable access .

This is because the space occupied by these primitive types is fixed, so they can be stored in a smaller memory area – the stack. This stores the values that facilitate quick lookup of variables.

2) Reference value: The object stored in the heap (heap), that is, the value stored at the variable is a pointer (point) to the memory address of the storage object.

This is because the size of the reference value will change, so it cannot be placed on the stack, otherwise it will reduce the speed of the variable search. Instead, the value placed in the stack space of the variable is the object

The address stored in the heap.

The size of the address is fixed, so storing it in the stack has no negative effect on the performance of the variable.

   b Different memory allocation mechanisms also bring different access mechanisms
1) in JavaScript, it is not allowed to directly access objects stored in the heap memory, so when accessing an object, the first is the object in the heap memory address, and then follow this address to get the value of this object, this is the legendary Access by reference。 2) and the value of the primitive type is directly accessible.    c different When copying variables 1) Original value: When a variable that holds the original value is copied to another variable, a copy of the original value is assigned to the new variable. Since these two variables are completely independent, they only have the same value. 2) Reference value: When you copy a variable that holds an object's memory address to another variable, the memory address is assigned to the new variable, which means that the two variables point to the same object in the heap memory, and any changes that they make will be reflected in the other. (one thing to understand here is that copying an object does not make an identical object in the heap memory, just a variable that holds pointers to the object). one more pointer.     The D parameter is passed differently (the process of copying the argument to the parameter)    First we should make it clear that the parameters of all functions in the ECMAScript are is passed by value.Of But why is there still a difference when it comes to values of primitive types and reference types?    It's not just the differences in memory allocations.  1) Original value: Just pass the value in the variable to the parameter, and then the parameter and the variable do not affect each other.    2) Reference value: Object variable The value inside it is the memory address of the object in the heap memory, which you should always keep in mind!      So the value that it passes is the memory address, which is why the changes to this parameter inside the function are external because they all point to the same object. Pass by value VS by reference

Pass-by-value is the most commonly used evaluation strategy: a function's formal parameter is a copy of the argument that was passed when it was called. Modifying the value of a parameter does not affect the argument.

When passed by reference (call by reference), the function's formal parameter receives an implicit reference to the argument, not the copy. This means that if the value of a function parameter is modified, the argument is also modified. Both points to the same value.

Passing by reference makes tracking of function calls more difficult and sometimes causes subtle bugs.

Pass-by-value due to the need to clone replicas each time, performance is low for some complex types. Both of these methods have their own problems.

The basic type is immutable  (immutable), only the object is mutable (mutable). Sometimes we try to "change" the contents of the string, but in JS,

Any "modify" operation that looks like a string value is actually creating a new string value. No method can change the value of a base type,

var str = "abc";    STR[0]; "A"    str[0] = "D";    Console.log (str); ABC     var name = ' Jozo ';    var upname=name.touppercase ();     Console.log (Upname,name); Output ' Jozo ' Jozo '

We cannot add properties and methods to the base type

var person = ' kn ';    Person.age =;    Person.method = function () {};     Console.log (Person.age); Undefined    console.log (person.method);//undefined

The value of the reference type is variable

var obj = {x:0};    obj.x = +;    var o = obj;    o.x = 1;    Console.log (obj.x)//1, modified    o = {x:100};  Equivalent to re-assigning, re-opening the memory, not modifying    Console.log (json.stringify (obj), json.stringify (o))//{"x": 1} {"X": []    obj.x;//1, Does not change because o = {"x": 100}

The value of a reference type is an object that is stored in both the stack memory and the heap memory

JavaScript differs from other languages in that it does not allow direct access to the in-memory location, which means that the object's memory space cannot be manipulated directly, so what do we do? In fact, it is a reference to the operand object,
So the value of the reference type is accessed by reference.
To be precise, the storage of reference types requires a stack of memory and a heap area (the heap is the heap memory in memory), and the stack memory holds the variable identifiers and pointers to the objects in the heap memory.
It can also be said to be the address of the object in heap memory.

If there are several objects:

var Person1 = {name: ' Jozo '};
var Person2 = {name: ' Xiaom '};
var Person3 = {name: ' Xiaoq '};

The three objects that are stored in memory are as follows:

var person1 =var person2 =//   False
Reference types are accessed by reference, in other words, if the address in the heap memory of the two objects is the same, it is clear that the Person1 and Person2 address in the heap memory are different.

The difference between the two data types in arguments and formal parameters first understand what arguments are and what are parameters. Arguments: Can be constants, variables, expressions, functions, and so on, regardless of the amount of the actual argument, they must have a definite value when making a function call to pass these values to the parameter. Therefore, an assignment, input, and so on should be used to obtain a definite value for the argument. Formal parameters: All called "formal arguments" are parameters that are used when defining function names and body functions to receive the arguments passed when the function is called. The function of formal parameters is to realize the relation between the key function and the modulated function, usually the data processed by the function, the factors affecting function function or the result of the function processing as the formal parameter.

When NUM is passed as an argument to the method Addnum is Param accepted as a formal parameter and is used in the body of the method, and NUM does not change globally, but when the argument is a reference type, the shape arguments is changed in the method body and the argument is changed.

The value is the basic data type function Addnum (param)  //param is the formal parameter {param+=10 relative to the Addnum method     ;    return param;} var num=10;  var result=addnum (num); Num is the actual parameter console.log (num) relative to the Addnum method;  Console.log (result);//20 value is a reference data type function fun (param)  //param is a formal parameter {      param[0]=99,    relative to the fun method; return param;  }  var num=[10];   var result=fun (num); In relation to the fun method, num is the argument console.log (Num[0]);  Console.log (result);//[99] 

Because the parameter of function in JS is a reference type, it can affect the argument! Infer the principle of parameters in callback, the following example modifies the variable data in the callback function;

function Fun (data,callback) {          var json=[1,2,3];          Callback (JSON)      }        var data=[];      Fun (Data,function (result) {          data=result;      })     Console.log (data)//[1, 2, 3]

Knowledge point 1, function is a data type, can be passed as a parameter 2, an array is a reference type 3, a reference type of the participation effect argument

1 <body> 2     <button onclick= ' log () ' >ajax</button> 3 </body> 4 <script> 5     function Fun (data,callback) {6         setTimeout (function () {7             var json=[1,2,3]; 8             Callback (JSON) 9         },4000)     }12     var data=[];14 fun     (data,function (res) {         data=res;16     })     Console.log (data) []18     function log () {         console.log (data)//[1, 2, 3]  4 seconds after output     }21 </script>

The original value and the reference value in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.