简体   繁体   中英

Javascript strings are primitive types?

In Javascript numbers strings and booleans are said to be primitive types. Primitive types are passed around by copy. OK consider the following code:

var s1 = "this is a string of 1000 characters ...";
var s2 = s1; // (2)

What happens in line (2)? 1000 characters are copied to the variable s2? OR is there one memory location and both s1 and s2 refer to this memory location? I believe the second is true. If so, why all books say that strings are primitive types, they are not, they are reference types, aren't they?

What happens in line (2)? 1000 characters are copied to the variable s2? OR is there one memory location and both s1 and s2 refer to this memory location?

It is an implementation detail of the JavaScript engine, there is no way to tell the difference from inside the JavaScript program.

why all books say that strings are primitive types

The language defines them as such .

they are reference types, aren't they?

They might be implemented that way at a level lower then is exposed to JS, but that doesn't matter to the JS author.

What happens in line (2)?

That's more or less implementation defined. To you , it will look like a copy. However, the engine is free to optimise it, and probably will. No doubt, something like copy-on-write .

In JavaScript, there are primitive strings and string objects. It's worth knowing the differences. A string object is passed around by reference, but seeing as all string methods return a new string, you're unlikely to modify it.

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