Javascript 更改字符串对象引用的基本字符串

Javascript 更改字符串对象引用的基本字符串,javascript,string,ecmascript-6,ecmascript-5,Javascript,String,Ecmascript 6,Ecmascript 5,忽略所有最佳实践,出于好奇,我有一个相当学术性的问题要问 如您所知,您可以向字符串对象添加自定义属性: var s = new String("initial string"); var s.customProperty = "Please Don't Forget about me"; 是否可以(不创建新的字符串对象)更改“s”引用的字符串原语 具体地说,我想更改“s”(如上),以便s==“新字符串”,但在进行此更改后,我希望s.customProperty仍然指向字符串原语:“请不要忘记我

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

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

var s = new String("initial string");
var s.customProperty = "Please Don't Forget about me";
是否可以(不创建新的字符串对象)更改“s”引用的字符串原语

具体地说,我想更改“s”(如上),以便s==“新字符串”,但在进行此更改后,我希望s.customProperty仍然指向字符串原语:“请不要忘记我”。同样,我希望在不创建任何新字符串对象的情况下实现这一点

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.customProperty = "Please Don't Forget about me";
"Your string".customProperty
然后你可以这样称呼它:

String.prototype.customProperty = "Please Don't Forget about me";
"Your string".customProperty
是否可以更改“s”引用的字符串原语

不可以。它包含的(ES6)/(ES5)是一个基因,不能突变

…而不必创建任何新的字符串对象

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
子类化,并覆盖所有引用可变属性的方法,但这个建议与“不要使用
String
对象”一样好。另请参见反问题的答案。

现在,您所有的
字符串
对象都具有该属性,我认为这不是OP所追求的。感谢您提供的信息性答案。转瞬即逝的思想…:有趣的是,如果字符串对象引用类似于对象属性的内容而不是内部插槽,则字符串对象将更加灵活。@LonnieBest:Immutability rules it all:-)如果您想要有状态的实例,只需将标准对象与
toString
方法结合使用即可。