为什么字符串类型返回功能

Why does typeof String return function

本文关键字:功能 返回 类型 字符串 为什么      更新时间:2023-09-26

为什么:

console.log( typeof String );当它是对象时返回function

字符串是字符串对象的构造函数。所有构造函数都是函数,因此您看到的是返回值。

您可以通过创建如下代码来自己看到这一点:

var MyObject = function (value) {
    this.value = value;
};
MyObject.prototype.getValue = function () {
    return this.value;
}
console.log(typeof(MyObject)); // function
console.log(typeof(new MyObject(1))); // object

这是因为字符串和"字符串"之间有很大的区别。让我详细说明一下:

console.log(typeof String)

将返回函数,而

console.log(typeof "String")

将返回字符串。

这是因为String实际上是一个全局构造函数。它用于创建字符串!

var string = new String('2 + 2'); // creates a String object
console.log(string);        // returns the string object. try it

"字符串"是一个字符串,因为javascript将其转换为字符串原语。

var string1 = '2 + 2'; // creates a String object
console.log(string1);        // returns the string primitive. try it
String()是一个

函数

JavaScript String()函数

String()函数将对象的值转换为字符串。

注意:String() 函数返回的值与单个对象的toString()值相同。

请参阅参考资料

你得到的typeof String构造函数是一个函数(请参阅此文档)。所有构造函数都是function的,这就是为什么如果你console.log(String),你会得到:

function String() { [native code] }

这显然是一个function.


如果要确定某物是否为字符串:

对于字符串文本,可以使用:

console.log(typeof 'foo');

或者,如果您有要测试的变量,请使用:

var str 'bar';
console.log(typeof str);

上述两个代码片段都将记录string