var getObjectClass = function (obj) {if (obj && obj.constructor && obj.constructor.toString()) {
/** for browsers which have name property in the constructor* of the object,such as chrome*/if(obj.constructor.name) {return obj.constructor.name;}var str = obj.constructor.toString();/** executed if the return of object.constructor.toString() is* "[object objectClass]"*/
if(str.charAt(0) == '['){var arr = str.match(/\[\w+\s*(\w+)\]/);} else {/** executed if the return of object.constructor.toString() is* "function objectClass () {}"* for IE Firefox*/var arr = str.match(/function\s*(\w+)/);}if (arr && arr.length == 2) {return arr[1];}}return undefined;};
function A() {this.getClass = function() {return this.constructor;}
this.getNewInstance = function() {return new this.constructor;}}
var a = new A();console.log(a.getClass()); // function A { // etc... }
// you can even:var b = new (a.getClass());console.log(b instanceof A); // truevar c = a.getNewInstance();console.log(c instanceof A); // true
从静态上下文:
function A() {};
A.getClass = function() {return this;}
A.getInstance() {return new this;}
Object.defineProperty(Object.prototype, "getClass", {value: function() {return this.constructor.name;}});
var x = new DOMParser();console.log(x.getClass()); // `DOMParser'
var y = new Error("");console.log(y.getClass()); // `Error'
function getClass(obj) {
// if the type is not an object return the typeif((let type = typeof obj) !== 'object') return type;
//otherwise, access the class using obj.constructor.nameelse return obj.constructor.name;}
它是如何运作的
构造函数有一个名为name访问的属性,它将为您提供类名。
更干净的代码版本:
function getClass(obj) {
// if the type is not an object return the typelet type = typeof objif((type !== 'object')) {return type;} else { //otherwise, access the class using obj.constructor.namereturn obj.constructor.name;}}