简体   繁体   中英

Are Array's & Objects the only non-primitives in Javascript?

I've been doing a lot of research on this topic for over 2 weeks now and I'm only asking the question because MDN's documentation on mutability says only arrays and objects are not primitive values and of course that's true, they have reference values.

However, I thought functions , string object , Date , and RegEx also had reference values because they are also non-primitives. For example if we use slice() on a string primitive, javascript will automatically convert(reassign) it to a string object and now it's mutable as the word 'snow' becomes 'know' through reassignment. This won't work with const because it disables reassignment.

let word = 'snow'
console.log(word) // "snow"
word = `k${word.slice(1)}`
console.log(word) // "know"

So I'm guessing either MDN is wrong or a lot of other resources like dotnettricks and even a few javascript certifications guides are wrong...

MDN isn't wrong - functions, Date and RegEx are objects.

Also, string is still primitive.

let a = 'snow';
let b = a;
a = 'know';
console.log(b); // snow

"strings" is primitive and new String("strings") is an object but in both cases the sequence of characters is immutable.

in your example you didn't really mutate the string you just create a new string and assign it to the same variable

var primitiveString = 'hello';
var objectString = new String('hello');
var objectStringRef = objectString;

// string are primitives so you can not add properties to it
primitiveString.newProperty = "my property";

console.log(primitiveString.newProperty) // undefined

// You can add properties to String objects
objectString.newProperty = "my property";

console.log(objectString.newProperty) // "my property"

// and you can have a reference to a String object
console.log(objectStringRef.newProperty) // "my property"

// but both are immutable
primitiveString[0] = "p";
objectString[0] = "p";

console.log(primitiveString) // "hello"
console.log(objectStringRef.toString()) // "hello"

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