Ignoring all best practices, I have a rather academic question that I'll ask for curiosity's sake.
As you know, you can add custom properties to a string Object:
var s = new String("initial string");
var s.customProperty = "Please Don't Forget about me";
Is it possible (without creating a new string object), to change the string-primitive that "s" references?
Specifically, I want to change "s" (above), so that s == "new string", yet after making this change, I want s.customProperty to still point to the string-primitive: "Please Don't Forget about me". Again, I want to achieve this without having to create any new string objects.
var s = new String("initial string");
var s.customProperty = "Please Don't Forget about me";
// What code must preceed the following "if statement" in order
// for it to return "true" (giving the restrictions I described
// in the paragraphs of this post)?
if(s == "new string" && s.customProperty == "Please Don't Forget about me")
{
console.log("true");
}
else
{
console.log("false");
}
In other words, is possible to change a string object's reference-pointer without losing or cloning all custom properties that have been added to that string object?
Is it possible to change the string-primitive that a "s" references?
No. The [[StringData]] (ES6) / [[PrimitiveValue]] (ES5) it contains is an internal slot and cannot be mutated.
… without having to create any new string objects.
There's no way around that.
What you possibly can do is to subclass String
and overwrite all methods to refer to a mutable property, but that advice is as good as "don't use String
objects". See also the answers to the inverse problem Is there a way to Object.freeze() a JavaScript Date?.