发布于 1年前

JavaScript获取Object类名的几种方法

有以下几种方法可以用来获取Object的类名:

  • typeof
  • instanceof
  • obj.constructor
  • func.prototype, proto.isPrototypeOf
  • func.name(ES6)

使用示例:

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"  这个适用于ES2015  

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42
©2020 edoou.com   京ICP备16001874号-3