将原始字符串更改为字符串对象引用

Changing the Primitive-String a String-Object References

忽略所有最佳实践,出于好奇,我有一个相当学术的问题。

如您所知,您可以向字符串对象添加自定义属性:

var s = new String("initial string");
var s.customProperty = "Please Don't Forget about me";

是否可以(不创建新的字符串对象)更改 "s" 引用的字符串基元?

具体来说,我想更改 "s"(以上),以便 s == "new string" ,但在进行此更改后,我希望 s.customProperty 仍指向字符串基元:"Please Don't Forget about me"。同样,我想实现这一点而不必创建任何新的字符串对象。

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");
}

换句话说,是否可以在不丢失或克隆已添加到该字符串对象的所有自定义属性的情况下更改字符串对象的引用指针?

String prototype 救援!

所以基本上是这样的:

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

那么你可以这样称呼它:

"Your string".customProperty

Is it possible to change the string-primitive that a "s" references?

没有。 [[StringData]] (ES6) / [[PrimitiveValue]] (ES5) it contains is an internal slot 且无法更改。

… without having to create any new string objects.

没有办法解决这个问题。

您可以做的是继承 String 并覆盖所有方法以引用可变 属性,但该建议与 "don't use String objects" 一样好。另见反问题的答案 .