如何使对象属性赋值保存引用而非值?(附伪代码示例)
Got it, let's figure out how to make data.num track changes to william.eyes! The core issue here is that basic types (like null, numbers, strings) are passed by value, not reference. When you assign william.eyes to data.num, you're just copying its current value—so later changes to william.eyes don't affect data.num at all.
Here are two straightforward solutions that don't involve arrays:
1. Wrap the value in an object (reference type)
Instead of storing eyes as a raw value, put it inside an object. Objects are reference types, so assigning the object to data.num will save a reference to the same object, not a copy of its value.
// Modified Pseudo Code class Human { constructor() { this.eyes = { value: null }; // Wrap the value in an object } addEye() { this.eyes.value = 1; // Update the object's inner value } } const william = new Human(); const data = { num: william.eyes }; // Save reference to the object william.addEye(); // Now data.num.value === 1 (tracks the change!)
This works because data.num points to the exact same object as william.eyes. Any updates to the object's properties are visible from both references.
2. Use a getter function for dynamic access
If you don't want to modify the Human class, you can turn data.num into a getter property. This way, every time you access data.num, it fetches the latest value of william.eyes dynamically.
// Pseudo Code with Getter class Human { constructor() { this.eyes = null; } addEye() { this.eyes = 1; } } const william = new Human(); const data = { get num() { // Define a getter for num return william.eyes; } }; william.addEye(); // Now data.num === 1 (always gets the current value!)
This approach keeps your original Human class intact, and data.num will always reflect the latest state of william.eyes whenever you access it.
Which one to choose?
- Use the object wrapper if you need to store a reference that you can update and check directly (you'll just access
data.num.valueinstead ofdata.num). - Use the getter if you want
data.numto behave like a direct "live" reference towilliam.eyeswithout nested properties.
内容的提问来源于stack exchange,提问作者Rami Chasygov

