如何在JavaScript中获取此对象的类型名称?

时间:2014-04-09 17:38:07

标签: javascript

如果实例化对象通过命名空间,我怎样才能获得它的类型名称?

考虑这两种声明继承的方式:

在模块之外

通过这种方式,有一个名为function的{​​{1}}对象,因此每当我要求Shark时,它都会返回myShark.constructor.name引用的函数的名称,constructor

Shark

在模块内

这一切都很好,但每当我在模块中声明一个继承结构时,我通常会按如下方式构造它。这个问题是// Fish function Fish() { this.fins; } Fish.prototype.swim = function() { console.log("Swim"); }; // Shark function Shark() { this.teeth; } Shark.prototype = new Fish; Shark.prototype.constructor = Shark; var myShark = new Shark(); console.log("My shark is: " + myShark.constructor.name); // Prints => My shark is: Shark 的构造函数引用了一个匿名函数。因此,每当我要求Yacht时,它都有一个空字符串。有没有办法让我仍能得到对象类型的myBoat.constructor.name表示?

String

我考虑过更改声明继承的方式,以便在模块中创建命名函数,然后通过var boats = (function() { exports = {}; // Boat exports.Boat = function() { this.crew = 1; }; exports.Boat.prototype.sail = function() { console.log("Sail"); }; // Yacht exports.Yacht = function() { this.decks = 4; }; exports.Yacht.prototype = new exports.Boat; exports.Yacht.prototype.constructor = exports.Yacht; return exports; }()); var myYacht = new boats.Yacht(); console.log("My boat is: " + myYacht.constructor.name); // Prints => My boat is: 公开它们,如下所示。有没有其他方法可以获得相同的结果没有必须创建命名函数然后将它们附加到导出?

exports

1 个答案:

答案 0 :(得分:1)

另一种方法是在函数表达式中使用名称:

// Yacht
exports.Yacht = function Yacht() {
   this.decks = 4;
};
exports.Yacht.prototype = new exports.Boat;
exports.Yacht.prototype.constructor = exports.Yacht; 
// incorrect: exports.Yacht.prototype.constructor = Yacht
// as the name is not in the scope

// ...
var myYacht = new boats.Yacht();
console.log("My boat is: " + myYacht.constructor.name);
// My boat is: Yacht

请注意,将名称添加到该函数不会将Yacht引入主函数的范围,因此它与您的第三个代码段中使用的函数声明方法不同。此外,它更简洁。 )

相关问题