JavaScript中是否有类似Java的class.getName()?
当前回答
你应该像这样使用somevar.constructor.name:
const getVariableType = a => a.constructor.name. tolowercase (); const d = new Date(); const res = getVariableType(d);/ /“日期” Const num = 5; const res2 = getVariableType(num);/ /“数量” Const fn = () => {}; const res3 = getVariableType(fn);/ /函数的 console.log (res1);/ /“日期” console.log(它);/ /“数量” console.log (res3);/ /函数的
其他回答
使用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
如果有人正在寻找使用jQuery的解决方案,这里是调整后的wiki代码(原来打破了jQuery)。
Object.defineProperty(Object.prototype, "getClassName", {
value: function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
}
});
好吧,伙计们,我一直在慢慢地建立一个catch all方法,这已经有几年了,哈哈!诀窍是:
有一个创建类的机制。 有一种机制来检查所有用户创建的类、原语和由本地构造函数创建/生成的值。 有一种机制可以将用户创建的类扩展为新的类,这样上述功能就可以渗透到你的代码/应用程序/库等中。
举个例子(或者看看我是如何处理这个问题的),看看github上的以下代码:https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js并搜索:
名为= classOf class sofis =,和或 defineSubClass =(不带反撇号('))。
As you can see I have some mechanisms in place to force classOf to always give me the classes/constructors type name regardless of whether it is a primitive, a user defined class, a value created using a native constructor, Null, NaN, etc.. For every single javascript value I will get it's unique type name from the classOf function. In addition I can pass in actual constructors into sjl.classOfIs to check a value's type in addition to being able to pass in it's type name as well! So for example:
' ' ' //请原谅长命名空间!直到用了一段时间后,我才知道它的影响(它们太糟糕了,哈哈)
var SomeCustomClass = sjl.package.stdlib.Extendable.extend({
constructor: function SomeCustomClass () {},
// ...
}),
HelloIterator = sjl.ns.stdlib.Iterator.extend(
function HelloIterator () {},
{ /* ... methods here ... */ },
{ /* ... static props/methods here ... */ }
),
helloIt = new HelloIterator();
sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`
sjl.classOfIs(helloIt, HelloIterator) === true; // `true`
var someString = 'helloworld';
sjl.classOfIs(someString, String) === true; // `true`
sjl.classOfIs(99, Number) === true; // true
sjl.classOf(NaN) === 'NaN'; // true
sjl.classOf(new Map()) === 'Map';
sjl.classOf(new Set()) === 'Set';
sjl.classOfIs([1, 2, 4], Array) === true; // `true`
// etc..
// Also optionally the type you want to check against could be the type's name
sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!
sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!
```
如果您有兴趣阅读更多关于我如何使用上面提到的设置,请查看repo: https://github.com/elycruz/sjljs
还有关于这个主题的书籍: - Stoyan Stefanov的《JavaScript模式》 - David Flanagan的《Javascript - The Definitive Guide》 ——还有其他很多人…(搜索le’web)。
你也可以快速测试我在这里谈论的功能: - http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (url中的0.5.18路径也有来自github的源代码,减去node_modules等)。
编码快乐!
下面是我提出的解决instanceof缺点的解决方案。它可以从跨窗口和跨框架检查对象的类型,并且在基本类型方面没有问题。
function getType(o) {
return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1];
}
function isInstance(obj, type) {
var ret = false,
isTypeAString = getType(type) == "String",
functionConstructor, i, l, typeArray, context;
if (!isTypeAString && getType(type) != "Function") {
throw new TypeError("type argument must be a string or function");
}
if (obj !== undefined && obj !== null && obj.constructor) {
//get the Function constructor
functionConstructor = obj.constructor;
while (functionConstructor != functionConstructor.constructor) {
functionConstructor = functionConstructor.constructor;
}
//get the object's window
context = functionConstructor == Function ? self : functionConstructor("return window")();
//get the constructor for the type
if (isTypeAString) {
//type is a string so we'll build the context (window.Array or window.some.Type)
for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) {
context = context[typeArray[i]];
}
} else {
//type is a function so execute the function passing in the object's window
//the return should be a constructor
context = type(context);
}
//check if the object is an instance of the constructor
if (context) {
ret = obj instanceof context;
if (!ret && (type == "Number" || type == "String" || type == "Boolean")) {
ret = obj.constructor == context
}
}
}
return ret;
}
isInstance需要两个参数:一个对象和一个类型。它工作的真正技巧是检查对象是否来自同一个窗口,如果不是,则获取对象的窗口。
例子:
isInstance([], "Array"); //true
isInstance("some string", "String"); //true
isInstance(new Object(), "Object"); //true
function Animal() {}
function Dog() {}
Dog.prototype = new Animal();
isInstance(new Dog(), "Dog"); //true
isInstance(new Dog(), "Animal"); //true
isInstance(new Dog(), "Object"); //true
isInstance(new Animal(), "Dog"); //false
type参数也可以是返回构造函数的回调函数。回调函数将接收一个参数,该参数是所提供对象的窗口。
例子:
//"Arguments" type check
var args = (function() {
return arguments;
}());
isInstance(args, function(w) {
return w.Function("return arguments.constructor")();
}); //true
//"NodeList" type check
var nl = document.getElementsByTagName("*");
isInstance(nl, function(w) {
return w.document.getElementsByTagName("bs").constructor;
}); //true
需要记住的一件事是IE < 9没有提供所有对象的构造函数,因此上面的NodeList测试将返回false,而且isInstance(alert,“Function”)也将返回false。
Agave.JS中的kind()函数将返回:
继承树中最接近的原型 对于'null'和'undefined'等始终为原始类型的类型,则为原始名称。
它适用于所有JS对象和原语,不管它们是如何创建的,并且没有任何惊喜。
var kind = function(item) {
var getPrototype = function(item) {
return Object.prototype.toString.call(item).slice(8, -1);
};
var kind, Undefined;
if (item === null ) {
kind = 'null';
} else {
if ( item === Undefined ) {
kind = 'undefined';
} else {
var prototype = getPrototype(item);
if ( ( prototype === 'Number' ) && isNaN(item) ) {
kind = 'NaN';
} else {
kind = prototype;
}
}
}
return kind;
};
例子:
数字
kind(37) === 'Number'
kind(3.14) === 'Number'
kind(Math.LN2) === 'Number'
kind(Infinity) === 'Number'
kind(Number(1)) === 'Number'
kind(new Number(1)) === 'Number'
NaN
kind(NaN) === 'NaN'
字符串
kind('') === 'String'
kind('bla') === 'String'
kind(String("abc")) === 'String'
kind(new String("abc")) === 'String'
布尔值
kind(true) === 'Boolean'
kind(false) === 'Boolean'
kind(new Boolean(true)) === 'Boolean'
数组
kind([1, 2, 4]) === 'Array'
kind(new Array(1, 2, 3)) === 'Array'
对象
kind({a:1}) === 'Object'
kind(new Object()) === 'Object'
日期
kind(new Date()) === 'Date'
功能
kind(function(){}) === 'Function'
kind(new Function("console.log(arguments)")) === 'Function'
kind(Math.sin) === 'Function'
未定义的
kind(undefined) === 'undefined'
null
kind(null) === 'null'