如何在Javascript中检查实例的类?

mko*_*mko 17 javascript

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

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

'this is an string'.class

=>String
Run Code Online (Sandbox Code Playgroud)

在js中有类似的东西吗?

Nat*_*all 39

你可能是指类型或构造函数,而不是类.类在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]"
Run Code Online (Sandbox Code Playgroud)

请参阅此相关的MDN文章.

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

要了解您拥有的原始类型,请使用typeof.这是使用字符串,布尔值,数字等最好的东西:

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

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

您也可以使用Object.getPrototypeOf(myObject)(myObject.__proto__或者myObject.constructor.prototype在某些浏览器getPrototypeOf中不支持时)获取原型(主干JavaScript继承).

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

new Date() instanceof Date;  // => true
Run Code Online (Sandbox Code Playgroud)

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

new Date().constructor.name;   // => 'Date'
Run Code Online (Sandbox Code Playgroud)


Koo*_*Inc 11

不确定这适用于所有浏览器,但您可以使用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
Run Code Online (Sandbox Code Playgroud)

虽然Object是Javascript中的所有人的母亲,但你可以扩展它(它有利有弊)

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

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

1来自ECMAScript标准.

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