我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
当前回答
对于ES6中的Javascript类,您可以使用object.constructor。在下面的示例类中,getClass()方法返回你所期望的ES6类:
var Cat = class {
meow() {
console.log("meow!");
}
getClass() {
return this.constructor;
}
}
var fluffy = new Cat();
...
var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();
ruffles.meow(); // "meow!"
如果你从getClass方法实例化类,请确保将其括在括号中,例如ruffles = new (fluffy.getClass())(args…);
其他回答
Javascript是一种无类语言:它不像Java那样有静态定义类行为的类。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。用JavaScript中的原型模拟许多基于类的特性是可能的。
在JavaScript中没有与Java的getClass()完全对应的方法。这主要是因为JavaScript是基于原型的语言,而Java是基于类的语言。
根据你需要getClass()做什么,JavaScript中有几个选项:
typeof 运算符 obj.constructor 函数。原型,proto.isPrototypeOf
举几个例子:
function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42
注意:如果你用Uglify编译你的代码,它会改变非全局类名。为了防止这种情况,Uglify有一个——mangle参数,你可以使用gulp或grunt将其设置为false。
你也可以这样做
Hello { 构造函数(){ } } 函数isClass (func) { 返回typeof func === 'function' && /^class\s/.test(function .prototype. tostring .call(func)) } console.log (isClass(你好))
这将告诉您输入是否是类
getClass()函数使用constructor.prototype.name
我找到了一种方法来访问类,比上面的一些解决方案要干净得多;在这儿。
function getClass(obj) {
// if the type is not an object return the type
if((let type = typeof obj) !== 'object') return type;
//otherwise, access the class using obj.constructor.name
else return obj.constructor.name;
}
它是如何工作的
构造函数有一个名为name access的属性,它将为您提供类名。
更简洁的代码版本:
function getClass(obj) {
// if the type is not an object return the type
let type = typeof obj
if((type !== 'object')) {
return type;
} else { //otherwise, access the class using obj.constructor.name
return obj.constructor.name;
}
}
同意dfa,这就是为什么我认为原型类,当没有命名类发现
下面是伊莱·格雷发布的一个升级版功能,以匹配我的思维方式
function what(obj){
if(typeof(obj)==="undefined")return "undefined";
if(obj===null)return "Null";
var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
if(res==="Object"){
res = obj.constructor.name;
if(typeof(res)!='string' || res.length==0){
if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
if(obj instanceof Array)return "Array";// Array prototype is very sneaky
return "Object";
}
}
return res;
}