以下是将字符串视为对象的两个原因.首先,您可以通过以下方式创建字符串:
var mystring = new String("asdf");
Run Code Online (Sandbox Code Playgroud)
我的印象是new运算符后面的构造函数必须返回一个对象.其次,字符串似乎有属性和方法.例如:
mystring.toUpperCase();
Run Code Online (Sandbox Code Playgroud)
但是,如果字符串是对象,那么我们期望像下面这样的东西起作用:
function string_constructor() {
return "asdf";
}
var mystring = new string_constructor();
Run Code Online (Sandbox Code Playgroud)
但它没有,我被告知它不是因为字符串不是对象.字符串对象是否也是如此?无论哪种方式,我怎样才能理解我列出的所有内容?
CMS*_*CMS 20
说到语言类型,字符串是 String类型的值.
该语言有五种基本类型,分别是String,Number,Boolean,Null和Undefined.
有String对象(也用于Number或Boolean),它们被称为原始包装器,它们是在使用与它们相关联的构造函数时创建的,例如:
typeof new String('foo'); // "object"
typeof 'foo'; // "string"
Run Code Online (Sandbox Code Playgroud)
但是不要与它们混淆,你很少需要使用原始包装器,因为即使原始值不是对象,你仍然可以访问它们的继承属性,例如,在字符串上,你可以访问所有成员String.prototype,例如:
'foo'.indexOf('o'); // 2
Run Code Online (Sandbox Code Playgroud)
这是因为属性访问器(在这种情况下为点)暂时将原始值转换为对象,以便能够indexOf在原型链中解析属性.
关于你的问题中的构造函数,如你所知,它不会返回字符串.
使用new运算符调用的函数返回一个隐式值,这是一个从该函数继承的新对象,prototype例如:
function Test () {
// don't return anything (equivalent to returning undefined)
}
new Test() instanceof Test; // true, an object
Run Code Online (Sandbox Code Playgroud)
如果从构造函数返回一个对象,那么新创建的对象(在构造函数中)将丢失,因此显式返回的对象将出现在函数中:
function Test2() {
return {foo: 'bar'};
}
new Test2().foo; // 'bar'
Run Code Online (Sandbox Code Playgroud)
但是在原始值的情况下,它们只是被忽略,并且隐式返回构造函数中的新对象(有关更多详细信息,请检查[[Construct]]内部操作,(参见步骤9和10)).