JavaScript中是否有类似Java的class.getName()?
当前回答
我用了一个小技巧:
function Square(){
this.className = "Square";
this.corners = 4;
}
var MySquare = new Square();
console.log(MySquare.className); // "Square"
其他回答
非常简单!
我最喜欢在JS中获取任何类型的方法
function getType(entity){
var x = Object.prototype.toString.call(entity)
return x.split(" ")[1].split(']')[0].toLowerCase()
}
我最喜欢的检查JS中任何类型的方法
function checkType(entity, type){
return getType(entity) === type
}
Jason Bunting的回答给了我足够的线索,让我找到我需要的东西:
<<Object instance>>.constructor.name
例如,在下面这段代码中:
function MyObject() {}
var myInstance = new MyObject();
myinstance。constructor.name将返回"MyObject"。
使用Object.prototype.toString
正如这篇文章所详述的那样,你可以使用Object.prototype.toString——toString的低级通用实现——来获取所有内置类型的类型
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
可以编写一个简短的辅助函数,例如
function type(obj){
return Object.prototype.toString.call(obj]).match(/\s\w+/)[0].trim()
}
return [object String] as String
return [object Number] as Number
return [object Object] as Object
return [object Undefined] as Undefined
return [object Function] as Function
Lodash有很多isMethods,所以如果你在使用Lodash,可能像这样的mixin会很有用:
// Mixin for identifying a Javascript Object
_.mixin({
'identify' : function(object) {
var output;
var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments',
'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber',
'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']
this.each(isMethods, function (method) {
if (this[method](object)) {
output = method;
return false;
}
}.bind(this));
return output;
}
});
它为lodash添加了一个名为“identify”的方法,其工作原理如下:
console.log(_.identify('hello friend')); // isString
砰砰作响: http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN
使用class.name。这也适用于function.name。
class TestA {}
console.log(TestA.name); // "TestA"
function TestB() {}
console.log(TestB.name); // "TestB"