字符串文字对象与否? [英] Are string literals objects or not?

查看:79
本文介绍了字符串文字对象与否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让我的JavaSscript基础变得强大。所以问题是关于字符串文字。他们不是对象?如果您的答案为是,那么我的问题是为什么 instanceof 返回 false

Trying to get my JavaSscript fundamentals strong. So the question is about string literals. Aren't they Objects? If your answer is 'yes' then my question is why is instanceof returning false?

> var s = new String
> s.constructor.toString()
function String() { [native code] }

> typeof s
object

> s instanceof String
true

> s instanceof Object
true

> s instanceof Number
false

到目前为止一切顺利。

> typeof 'c'
string

> 'c' instanceof Object
false

> 'c' instanceof String
false

> 'c'.length
1

> 'c'.charAt(0)
c

> 'c'.constructor.toString()
function String() { [native code] }


推荐答案

字符串文字是原语(可以创建字符串值),字符串对象使用新增的字符串构造函数 表达式:

String literals are primitives (String values), String objects can be created with the String constructor in a new expression:

"foo" instanceof String // false

new String("foo") instanceof String // true

编辑:某事这似乎令人困惑(通过查看已接受的答案此处),您仍然可以访问原始值的原型对象上定义的属性,例如:

Something that seems to be confusing (by looking at the accepted answer here), is that you can still access properties defined on the prototype objects of primitive values, for example:

"foo".indexOf == String.prototype.indexOf // true
"foo".match == String.prototype.match // true
String.prototype.test = true;
"foo".test // true
true.toString == Boolean.prototype.toString
(3).toFixed == Number.prototype.toFixed // true
// etc...

其原因依赖于属性访问者,点符号和括号表示法 []

The reason of that relies on the Property Accessors, the dot notation . and the bracket notation [].

让我们看看ECMA-262规范中的算法:

Let's give a look to the algorithm in the ECMA-262 specification:

生产MemberExpression:MemberExpression [Expression](或MemberExpression。标识符)的评估如下:

The production MemberExpression : MemberExpression [ Expression ] (or MemberExpression . Identifier) is evaluated as follows:


  1. 评估 MemberExpression

致电 GetValue(结果(1))

评估表达。

调用 GetValue(Result(3))

调用 ToObject(结果(2))

致电 ToString(结果(4))

返回一个值类型为Reference的基础对象为Result(5)且其属性名称为 Result(6)

Return a value of type Reference whose base object is Result(5) and whose property name is Result(6).

第5步中, ToObject 内部运算符类型 - 将MemberExpression转换为object,具体取决于它的类型。

In the Step 5, the ToObject internal operator type-converts the MemberExpression to object, depending on it's type.

原语在没有注意的情况下转换为对象,这就是为什么你可以访问原型上定义的属性。

The primitives are converted to Objects without noticing, and that's why you can access the properties defined on the prototype.

这篇关于字符串文字对象与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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