26

可能重复:
如何获取 JavaScript 对象的类?

在 Ruby 中,我可以这样做来检查实例的类:

'this is an string'.class

=>String

js中有没有类似的东西?

4

4 回答 4

44

您可能是指类型或构造函数,而不是类。类在 JavaScript 中有不同的含义。

获取课程:

var getClassOf = Function.prototype.call.bind(Object.prototype.toString);
getClassOf(new Date());     // => "[object Date]"
getClassOf('test string');  // => "[object String]"
getClassOf({ x: 1 });       // => "[object Object]"
getClassOf(function() { }); // => "[object Function]"

请参阅这篇相关的 MDN 文章。

要获取构造函数或原型,有多种方法,具体取决于您的需要。

要发现您拥有的原语类型,请使用typeof. 这是与字符串、布尔值、数字等一起使用的最佳方法:

typeof 'test string';  // => 'string'
typeof 3;              // => 'number'
typeof false;          // => 'boolean'
typeof function() { }; // => 'function'
typeof { x: 1 };       // => 'object'
typeof undefined;      // => 'undefined'

请注意,null在这种情况下行为很奇怪,因为typeof null会给你"object",而不是"null".

Object.getPrototypeOf(myObject)您还可以使用(myObject.__proto__myObject.constructor.prototype在某些getPrototypeOf不支持的浏览器中)获取原型、主干 JavaScript 继承。

您可以使用以下命令测试构造函数instanceof

new Date() instanceof Date;  // => true

您也可以使用 合理地获取构造函数myObject.constructor,但请注意这可以更改。要获取构造函数的名称,请使用myObject.constructor.name.

new Date().constructor.name;   // => 'Date'
于 2012-08-18T13:17:05.257 回答
18

不确定这是否适用于所有浏览器,但您可以使用constructor.name

'some string'.constructor.name; //=>String
({}).constructor.name           //=>Object
(7.3).constructor.name          //=>Number
[].constructor.name             //=>Array
(function(){}).constructor.name //=>Function
true.constructor.name           //=>Boolean
/test/i.constructor.name        //=>RegExp
(new Date).constructor.name     //=>Date
(new function MyConstructor(){}())
  .constructor.name;            //=>MyConstructor

虽然Object是 Javascript 中的一切之母,但您可以扩展它(它有优点也有缺点

Object.prototype.class = function(){
  return this.constructor.name;
}
'some string'.class(); //=>String
(23).class();          //=>Number
// etc...

注意:javascript 不知道 'classes' 1,它的继承模型是原型的

1来自 ECMAScript 标准。

ECMAScript 不使用 C++、Smalltalk 或 Java 中的类。相反,可以通过各种方式创建对象,包括通过文字符号或通过构造函数创建对象,然后执行代码,通过将初始值分配给它们的属性来初始化它们的全部或部分。每个构造函数都是一个具有名为原型的属性的函数,用于实现基于原型的继承和共享属性。对象是通过在 new 表达式中使用构造函数来创建的;例如, new Date(2009,11) 创建一个新的 Date 对象。在不使用 new 的情况下调用构造函数会产生依赖于构造函数的后果。例如,Date() 生成当前日期和时间的字符串表示,而不是对象。

于 2012-08-18T13:11:46.303 回答
3

typeofinstanceof这就是你需要的

> x = "Hello, World!"
"Hello, World!"
> typeof x
"string"

您可以检查构造函数名称以获取构造函数类的名称(或您所称的类):

> x.constructor.name
> "String"
于 2012-08-18T12:58:20.610 回答
3

在 js 中,您可以使用:

typeof

等式。

var a="this is string";
typeof a; // return "string"

function abc(){}
typeof abc; // return "function"

var a = {a:1,b:2,c:3}
typeof a; return "object"
于 2012-08-18T13:01:59.703 回答