简体   繁体   English

我如何获得原始值的参考?

[英]how do i get a reference of primitive value?

var number = 12345;

var obj = {};

do something like 做点什么

obj.look    ((((((some operator or function to get a reference of number )))))      number

anyway, let's think now obj has a reference to number. 无论如何,让我们想想现在obj有一个数字的参考。
so I would like to wanna do it this way. 所以我想这样做。

obj.look = 'abc';

console.log (number); // hopefully  'abc'

i would like it's gonna be: 我希望它会是:

  1. not method ( like obj.look() ) 不是方法(比如obj.look())
  2. but can refer in property ( like obj.look ) 但可以参考财产(如obj.look)

    all I'm asking is how to get a reference of primitive value. 所有我要问的是如何获得原始价值的参考。
    I believe there must be some way. 我相信必须有某种方式。 please help me out. 请帮帮我。

You can use Object.defineProperty : 您可以使用Object.defineProperty

 var number = 12345; var obj = {}; Object.defineProperty(obj, 'look', { get() { return number; }, set(value) { number = value; } }); document.write(obj.look + '<br>'); obj.look = 'abc'; document.write(number); 

You can have an object, copy that reference to another variable, mutate the object and since both variables hold a reference to the same object any changes done from one variable will also be accessible from the other variable. 您可以拥有一个对象,将该引用复制到另一个变量,改变该对象,并且因为两个变量都持有对同一对象的引用,所以从一个变量完成的任何更改也可以从另一个变量访问。

Primitive values can be wrapped into objects ( new Object ) but they can not be referenced otherwise. 原始值可以包装到对象( new Object )中,但不能以其他方式引用它们。 String objects are immutable (all properties are non-configurable, non-writable) and Number objects values are not accessible either. 字符串对象是不可变的(所有属性都是不可配置的,不可写的),并且也无法访问Number对象值。 So you can't change the value of either object. 所以你不能改变任何一个对象的价值。

That means when you do: 这意味着当你这样做:

obj.look = 'abc';

You are wiping the old reference and setting up a new string there (object or primitive). 您正在擦除旧引用并在那里设置新字符串(对象或基元)。 number will still hold the old reference and will remain unchanged. number仍将保留旧参考,并将保持不变。

So, no. 所以不行。 I don't think this is possible to do in Javascript. 我不认为这可以用Javascript做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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