From an error-prone title says js data, variables and memory

Speaking from an error-prone title

  1. topic
var a={name:'A'}
function fn(obj){
	obj={name:'B'}
}
fn(a)
console.log(a.name)
  1. answer
 A
  1. Resolve

Definition of variables:
A variable, {name: 'A'} of the data, the data type for the object;
Fn is a function declarations (name), Fn () function is executed.
Implementation process:
(1) A variable assignment. The {name: 'A'} save the object to the heap memory, and the heap memory address (e.g., 0x111) assigned to a variable in the memory stack --a: 0x111
(2) before execution fn, fn not take up memory ; fn when executed, generate a new parameter variable obj, after passing arguments a, i.e. execution obj = a, a content transmitted to the obj - obj: 0x111
(. 3) performs the function statement obj = {name : 'B'}. I.e., the (1) once again during the execution of the assignment, the {name: 'B'} address (e.g., 0x222) is saved to the obj --obj: 0x222
(. 4) performed a.name statement. The value of a (0x111) to find the corresponding heap {name: 'A'}, to obtain the value A.
(5) fn executed, a local variable obj is automatically released, pointing obj heap {name: 'B'} will become garbage objects, garbage and recycling recovery period, to free memory. And as a global variable it will always exist.

  1. Extended
var a={name:'A'}
function fn(obj){
   obj.name='B'
}
fn(a)
console.log(a.name)
答案为B 

Simple analysis, the same content and a obj (i.e., the same address), pointing to the same pile of memory, change the heap memory, then (B becomes), B also becomes a.name

Released three original articles · won praise 1 · views 38

Guess you like

Origin blog.csdn.net/m0_46083198/article/details/104608329
Recommended