Setting a variable equal to another variable

后端 未结 3 1367
孤街浪徒
孤街浪徒 2020-12-03 15:53

I have a few questions about setting a variable equal to another variable in JavaScript.

Let\'s say we create an object, a and set b = a.

3条回答
  •  醉话见心
    2020-12-03 16:23

    Let me try to explain:

    1) In your example a and b are references to one and the same object, while a.fname (or b.fname) is an attribute of that object. So when manipulating the attribute it will be changed in the object, while the references won't be affected, they still point to the same object, the object itself has been changed. a = {} on the other hand will just replace the reference to the object without affecting the object itself or b's reference to It.
    It's no clearance btw you only just created a new reference to a new empty object.

    2) These are not objects, so there is no reference you are directly manipulating the values. That' s because there's a difference between objects and primitives which might get confusing especially in the beginning if you're not used to working with strict types.

提交回复
热议问题