简体   繁体   中英

How to access properly to javascript class values

I was setting up a class constructor for handling my database, I did, but on the road I got some doubts about javascript's behavior.

To better understand the problem I reduced everything to its minimal expression. Here is the core:

name.js

class Name {
    constructor(){
        this.value = 'mo'
    }
    setName(){
        this.value = 'moom'
    }
}

export default new Name()

sayName.js

import name from './name'

const outsideName = name.value

function sayName(){
    const insideName = name.value
    console.log(insideName) // => moon
    console.log(outsideName) // => mo
}

export default sayName

index.js

import name from './name'
import sayName from './sayName'

name.setName()
sayName()

I was expecting to get the same output value from the console(moon). Why are the outputs from the console different(mo !=== moon)? I'd appreciate it if you could help me with this.

  1. You create an instance of Name
  2. You copy the value of its name property (mo) to outsideName
  3. You call name.setName() which changes the value of its name property to moon.
  4. You log the value of its name property.
  5. You log the value of outsideName

Since you never change outsideName after step 2, it doesn't change.


I reduced everything to its minimal expression.

You can reduce it further.

 let object = { foo: 1 }; let value = object.foo; object.foo = 2; console.log( object.foo, value); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM