如何获得JavaScript对象的类? [英] How to get a JavaScript object's class?

查看:141
本文介绍了如何获得JavaScript对象的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个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是基于原型的语言,而不是Java是< a href =http://en.wikipedia.org/wiki/Class-based_programming =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() for,JavaScript中有几个选项:

Depending on what you need getClass() for, there are several options in JavaScript:

  • typeof
  • instanceof
  • obj.constructor
  • 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 grunt

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆