Data, variables, memory

data

Stored in memory representing specific information, essentially 0101…

Transitive, operable

var a  = 3
var b = a + 2
Copy the code

All operations in memory are targeted at data: arithmetic operations, logic operations, assignment operations, running functions

memory

Space that can temporarily store data

Memory classification

  • Stack: global/local variables
  • Object heap:

variable

Variable quantity, consisting of variable name and variable value, each variable corresponds to a small piece of memory, variable name is used to find the corresponding memory, variable value is the data stored in the memory

The relationship between memory, data and variables

  • Memory The space used to store data
  • Variables are memory identifiers

thinking

Var a = XXX, what does a hold in memory?

  • When XXX is basic data: save this data
  • When XXX is an object: store the address value of the object
  • When XXX is a variable: hold the memory contents of XXX (base data/address value)

Reference variable assignment

  • Change attributes
varObj1 = {name:'Tom'var obj2 = obj1
obj1.name = 'Jack'
console.log(obj2.name) // Jack, obj1 and obj2 refer to the same object
Copy the code
  • Change the address
varObj1 = {age:18varObj2 = obj1 obj1 = {age:20console.log(obj1.age, obj2.age) Obj1 = age = 20; obj2 = age = 18
Copy the code

Reference variable passing

  • Change attributes
var obj1 = { age: 18 }
var obj2 = obj1
function fun(obj) {
    obj.age = 20
}
fun(obj1)
console.log(obj1.age, obj2.age) / / 20, 20
// Obj1 and obj2 point to objects whose addresses remain unchanged
Copy the code
  • Change the address
var obj1 = { age: 18 }
var obj2 = obj1
function fun(obj) {
    obj = { age: 20 }
}
fun(obj1)
console.log(obj1.age, obj2.age) / / 18, 18
// redirect obj to {age: 20}
// variables obj1, obj2 still point to {age: 18}
Copy the code