如何获取 JavaScript 对象的类? [英] How to get a JavaScript object's class?
问题描述
我创建了一个 JavaScript 对象,但如何确定该对象的类?
I created a JavaScript object, but how I can determine the class of that object?
我想要类似于 Java 的 .getClass()
方法.
I want something similar to Java's .getClass()
method.
推荐答案
Java 的 getClass()
在 JavaScript 中.这主要是因为 JavaScript 是一种基于原型的语言,而 Java 是一种<一个 href="http://en.wikipedia.org/wiki/Class-based_programming" rel="noreferrer">基于类 一个.
There's no exact counterpart to Java's getClass()
in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.
根据您需要 getClass()
的用途,JavaScript 中有几个选项:
Depending on what you need getClass()
for, there are several options in JavaScript:
typeof
instanceof
obj.
<代码>构造函数func.
prototype
,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
参数,您可以将其设置为false 使用 gulp 或 咕噜声.
Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle
param that you can set to false is using gulp or grunt.
这篇关于如何获取 JavaScript 对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!