JavaScript中String对象的属性值 [英] Property value of a String object in JavaScript

查看:133
本文介绍了JavaScript中String对象的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,每个字符串都是Javascript中的对象。尽管如此,它仍然按预期的那样起作用:

As far as I understand, every string is an object in Javascript. Still, it "does not work" as I expect it to be:

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"

但是,如果我尝试以错误的方式定义字符串,一切按预期工作

However, if I try to define a string in the "wrong way", everything works as expected

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

为什么会这样?

推荐答案

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

You may be interested in checking out the first part of this article:

  • The Complete Javascript Strings Reference

引用:


有两种不同类型的字符串,其行为完全不同。只需在字符串周围使用引号即可创建文字。通过隐式使用new关键字创建对象。如果使用String关键字将字符串赋值给变量,则不使用new关键字,括号内容将转换为字符串文字。

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.

字符串文字可以访问所有字符串的对象和方法,因为javascript会暂时将字符串文字强制转换为字符串对象,以便运行所需的方法。

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.

两者的不同之处在于它们的处理方式新的属性和方法。与所有Javascript对象一样,您可以将属性和方法分配给任何String对象。

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.

无法向字符串文字添加属性或方法的原因是当您尝试访问文字的属性或方法时, Javascript解释器临时将字符串的值复制到新对象中,然后使用该对象的属性或方法。这意味着String文字只能访问字符串的默认属性或方法以及已添加为原型的那些。

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中String对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆