How to check the class of an instance in Javascript?
Possible Duplicate:
How to get a JavaScript Object's Class?
在Ruby中,我可以这样做来检查实例的类:
1 2 3 | 'this is an string'.class =>String |
JS中有类似的东西吗?
您可能指的是类型或构造函数,而不是类。类在JavaScript中有不同的含义。
要获得课程:
1 2 3 4 5 | 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文章。
要获得构造函数或原型,有几种方法,这取决于您需要什么。
要了解您拥有的原始类型,请使用
1 2 3 4 5 6 | typeof 'test string'; // => 'string' typeof 3; // => 'number' typeof false; // => 'boolean' typeof function() { }; // => 'function' typeof { x: 1 }; // => 'object' typeof undefined; // => 'undefined' |
注意,在这种情况下,
您还可以在某些浏览器中使用
您可以使用
1 | new Date() instanceof Date; // => true |
您也可以使用
1 | new Date().constructor.name; // => 'Date' |
不确定是否适用于所有浏览器,但您可以使用
1 2 3 4 5 6 7 8 9 10 | '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 |
虽然
1 2 3 4 5 6 | Object.prototype.class = function(){ return this.constructor.name; } 'some string'.class(); //=>String (23).class(); //=>Number // etc... |
注意:javascript不知道'classes'1,它的继承模型是原型。
1来自ECMAScript标准。
ECMAScript does not use classes such as those in C++, Smalltalk, or
Java. Instead objects may be created in various ways including via a
literal notation or via constructors which create objects and then
execute code that initialises all or part of them by assigning initial
values to their properties. Each constructor is a function that has a
property named prototype that is used to implement prototype-based
inheritance and shared properties. Objects are created by using
constructors in new expressions; for example, new Date(2009,11)
creates a new Date object. Invoking a constructor without using new
has consequences that depend on the constructor. For example, Date()
produces a string representation of the current date and time rather
than an object.
在JS中,您可以使用:
1 | typeof |
情商
1 2 3 4 5 6 7 8 | 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" |
你需要的是
1 2 3 4 | > x ="Hello, World!" "Hello, World!" > typeof x "string" |
您可以检查构造函数名称以获取构造函数类的名称(或您所调用的类的名称):
1 2 | > x.constructor.name >"String" |