Reputation: 26867
How can I get the type name of an instantiated object whenever it has been through a namespace?
Consider these two ways of declaring inheritence:
Outside of a module
With this way, there is a function
object that is named Shark
so whenever I ask for myShark.constructor.name
, it returns the name of the function that constructor
is referencing, which is 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
Inside a module
That's all fine, but whenever I declare an inheritance structure inside of a module, I usually structure it as below. The problem with this is that the constructor for Yacht
references an anonymous function. Therefore, whenever I ask for the myBoat.constructor.name
it has an empty string. Is there a way that I can still get a String
representation of the object's type?
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:
I have considered changing how I declare inheritance so that I create named functions inside the module and then expose them through exports
as below. Is there any other way to get the same result without having to make named functions and then attaching them to exports?
var drinks = (function() {
var exports = {};
// Drink
function Drink() {
this.calories = 130;
}
// Beer
function Beer() {
this.alcohol = 8;
}
Beer.prototype = new Drink;
Beer.prototype.constructor = Beer;
exports.Drink = Drink;
exports.Beer = Beer;
return exports;
}());
var myBeer = new drinks.Beer();
console.log("My drink is: " + myBeer.constructor.name);
// Prints => My drink is: Beer
Upvotes: 1
Views: 74
Reputation: 106365
An alternative would be using names in function expressions:
// 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
Note that adding the name to that function won't introduce Yacht
into the main function's scope, so it's not the same as function declaration approach used in your third code snippet. Besides, it's more concise. )
Upvotes: 1