1

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?

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97

2 Answers2

4

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?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for the informative answer. Fleeting thoughts . . . : String objects would be interestingly more flexible if they referenced something similar to an object-property instead of an internal slot. – Lonnie Best May 27 '16 at 13:05
  • 1
    @LonnieBest: Immutability rules it all :-) If you want stateful instances, just use standard objects with a `toString` method. – Bergi May 27 '16 at 15:18
-1

String prototype to the rescue!

So basically something like this:

String.prototype.customProperty = "Please Don't Forget about me";

Then you can call it like this:

"Your string".customProperty
Juha Tauriainen
  • 1,581
  • 1
  • 12
  • 14