You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使对象属性赋值保存引用而非值?(附伪代码示例)

解决基本类型的"引用保存"需求

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.value instead of data.num).
  • Use the getter if you want data.num to behave like a direct "live" reference to william.eyes without nested properties.

内容的提问来源于stack exchange,提问作者Rami Chasygov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:10:38