Reputation: 1680
I was wondering if the following situation is possible. I am trying to write a object factory, that will construct different types of objects. What I am trying to figure out, is if it is possible in java script to set the type as something other then a function or object? Similar to in C# how a class instance of Car is a typeof Car, even though the base type is object. Hopefully I am explaining this clearly. The best way to explain it, is demonstrated below:
var object = function(){
switch(id){
case 1:
$_objInstance = new Car();
break;
case 2:
$_objInstance = new Animal();
break;
return $_objInstance;
}
function Car(){
this.Name = "GM";
}
document.write(object instanceof Car);
or
typof(
object) == Car //is this possible?
Thanks in advance! Happy coding:)
Upvotes: 0
Views: 99
Reputation: 1075189
What I am trying to figure out, is if it is possible in java script to set the type as something other then a function or object?
No, you can't. However:
JavaScript does have an instanceof
operator you can use to test an instance to see if it's likely to have been constructed by a given constructor:
if (obj instanceof Car) {
// ...
}
Function#name
remains unreliable in the wild (in that JavaScript engines don't set it reliably yet), you but you set it explicitly on your constructor functions:
Car.name = "Car";
...and then use obj.constructor.name
to find the name of the constructor. That relies on the object inheriting the constructor
property correctly, which it will if you don't mess up the default object on the function's prototype
property.
Several years back I wrote a blog post about typeof
, instanceof
, Object.prototype.toString
, and various other ways you can use to determine what something is, although I left off that option of just setting your own name.
Here's an example of using .constructor.name
:
function Car() {
}
Car.name = "Car";
function Animal() {
}
Animal.name = "Animal";
console.log("Randomly constructing 10 Cars or Animals:");
for (var n = 0; n < 10; ++n) {
var x = Math.random() < 0.5 ? new Car() : new Animal();
console.log("We got: " + x.constructor.name);
}
When I said above
That relies on the object inheriting the
constructor
property correctly, which it will if you don't mess up the default object on the function'sprototype
property.
let me give you an example that messes it up, so you know what to keep an eye out for. You routinely see people doing this:
// PROBLEMATIC: Wipes out the `constructor` property
function Car() {
}
Car.prototype = {
drive: function() {
}
// ...
};
That is, rather than augmenting the object that Car.prototype
got originally, they replace it. I prefer to augment (e.g., don't replace the whole object, just add properties to it), for various reasons, but if you do replace it you can just make sure you give the new one the correct constructor
:
// Keeps `constructor` correct
function Car() {
}
Car.prototype = {
constructor: Car,
drive: function() {
}
// ...
};
Upvotes: 1