JavaScript中是否有类似Java的class.getName()?
当前回答
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
其他回答
可以时使用constructor.name,不能时使用regex function。
Function.prototype.getName = function(){
if (typeof this.name != 'undefined')
return this.name;
else
return /function (.+)\(/.exec(this.toString())[1];
};
我用了一个小技巧:
function Square(){
this.className = "Square";
this.corners = 4;
}
var MySquare = new Square();
console.log(MySquare.className); // "Square"
比如你有var obj;
如果你只想知道obj的类型名称,比如“Object”、“Array”或“String”, 你可以用这个:
Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');
使用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