引用变量

Referencing variables

本文关键字:变量 引用      更新时间:2023-09-26

在许多其他编程语言中,可以通过副本或引用获得变量的值。

示例(PHP):

$value = 'a value';
$copy = $value;
$ref = &$value;
$value = 'new value';
echo $copy; // 'a value'
echo $ref; // 'new value'

JavaScript中有类似的功能吗?我可以引用对象的属性吗?即使我用新的字符串/对象替换该属性,引用的变量也会指向新数据吗?

以下是我试图实现的示例代码:

var obj = { property: 'a value' }
var another = obj.property // save this by reference to this variable
obj.property = 'new value'
console.log(another) // expected: 'new value'

到目前为止,我已经尝试过使用getters/ssetters,但这并没有帮助,因为当我将属性分配给一个新变量时,getter会被调用并返回实际值。我确信使用Node.js EventEmitter或使用函数调用而不是属性可以很容易地实现这一点,但我确实在寻找我可能错过的某种语言功能,或者寻找一些明显、简单的方法来完成这些事情。

谢谢!

在Javascript中,对象是通过引用传递的,但基元(字符串、数字和布尔值)是通过值传递的:

var obj = { property: 'a value' };
var another = obj.property; // value
obj.property = 'new value';
console.log(another); // gives a value

但是

var obj = { property: 'a value' };
var another = obj; // reference
obj.property = 'new value';
console.log(another.property); // gives new value