试图让我的JavaSscript基础变得强大.所以问题是关于字符串文字.不是Objects吗?如果你的回答是'是'那么我的问题是为什么要instanceof回来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
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.
> 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] }
Run Code Online (Sandbox Code Playgroud)
字符串文字是基元(字符串值),可以使用表达式中的String构造函数创建String对象:new
"foo" instanceof String // false
new String("foo") instanceof String // true
Run Code Online (Sandbox Code Playgroud)
编辑:似乎令人困惑的东西(通过查看此处接受的答案),您仍然可以访问原始值的原型对象上定义的属性,例如:
"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...
Run Code Online (Sandbox Code Playgroud)
其原因依赖于Property Accessors,点表示法. 和括号表示法[].
让我们看一下ECMA-262规范中的算法:
生成MemberExpression:MemberExpression [Expression](或MemberExpression.标识符)的计算方法如下:
评估MemberExpression.
打电话GetValue(Result(1)).
评估表达.
打电话GetValue(Result(3)).
打电话ToObject(Result(2)).
打电话ToString(Result(4)).
返回类型为Reference的值,其基础对象为Result(5)且其属性名称为Result(6).
在步骤5中,ToObject内部运算符将MemberExpression类型转换为对象,具体取决于它的类型.
基元在没有注意的情况下转换为对象,这就是您可以访问原型上定义的属性的原因.