简体   繁体   中英

To what types do the references get assigned instead of being copied in Javascript?

I am on my mobile phone, so I can't test for myself. Also, I might miss something.

I know that when a number is being assigned, say a = b, b is actually copied into a. But, if b was an object, just a reference wouls be passed. What with other types? Is there something I should worry about?

Also, I heard that you can't use pointers in C# because variables get moved around by the JC. Is it the same in Javascript? How are these references solved in these languages then?

javascript According to specification, you have types: undefined, null, boolean, string, number, object. You can think of them as immutable except object, which is practically just a (hash)map. So yes, if you assign variable, it's "copied" (you don't care if it really is) unless it's an object type. Take example:

var x = "hello";
var y = x; //copy or reference, who cares?
x += " world"; //new string object, x references it
alert(y); //alerts hello

C# According to C# 2.0 specification, there are struct/value types and class/reference types . So, from practical point of view, variable of value type actually stores the data on the call stack (and gets copied on assignment), and variable of reference types is just a reference (and data goes to heap). Example:

int holds_a_value = 5;
StringBuilder holds_a_reference = new StringBuilder();

You can use pointers in C# (pointer = reference), but you have to pin them if you call unsafe functions outside .net / C# , or using unsafe code. eg:

fixed (int* p = something) { /*p is safe to use, memory doesn't move */}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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