gpt4 book ai didi

javascript - JavaScript 中 String 对象的属性值

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:34 26 4
gpt4 key购买 nike

据我了解,每个字符串都是 Javascript 中的一个对象。尽管如此,它仍然“不起作用”,正如我所期望的那样:

var a="abc";  //here we get a new string object
a.b = 123; //I seem to declare a property "b" of that object
alert(a.b); //alerts "undefined"

但是,如果我尝试以“错误的方式”定义字符串,一切都会按预期进行

var a=new String("abc"); //
a.b = 123;
alert(a.b); //alerts "123"

为什么会这样?

最佳答案

您可能有兴趣查看本文的第一部分:

引用:

There are two different types of Strings and the behave quite differently. A literal is created just by using quotes around your string. An object is created by implicit use of the new keyword. If you assign a string to a variable using the String keyword, without the new keyword the contents of the parenthesis will be cast as a string literal.

A string literal has access to all of a string's objects and methods because javascript will temporarily cast a string literal as a string object in order to run the desired method.

Where the two differ is their treatment of new properties and methods. Like all Javascript Objects you can assign properties and methods to any String object.

You can not add properties or methods to a string literal. They are ignored by the interpreter.

The reason you can't add properties or methods to a string literal is that when you try to access a literal's property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object's properties or methods. This means a String literal can only access a string's default properties or methods and those that have been added as prototypes.

关于javascript - JavaScript 中 String 对象的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com