I have a javascript function with a variable 'object' which may recieve any of two types of object ,say x and y object
function myFunction(object){alert(instanceof object) };
Is there something like this? It should alert x or y
I have a javascript function with a variable 'object' which may recieve any of two types of object ,say x and y object
function myFunction(object){alert(instanceof object) };
Is there something like this? It should alert x or y
Is there something like this? It should alert x or y
Yes:
alert(object instanceof TheConstructorYouWantToCheckAgainst);
If I read your question correctly, your constructors are x
and y
(convention would be to use an upper case first letter). So for instance:
function x() {
}
function y() {
}
var o = new x();
console.log(o instanceof x); // true
console.log(o instanceof y); // false
If you want to get "x"
from object
when it's created via new x
, you can't reliably in ES5 and before. In ES2015 (aka "ES6") and above, functions have a name
property which is set in a large variety of ways (even when the function was created with an "anonymous" function expression). So if x
has a name (it's still possible for it not to), and if the inheritance chain has been correctly set up, object.constructor.name
will give you "x"
. But I wouldn't rely on it, because people mess up constructor
when doing inheritance chains all the time.
You can use different solution depending on what you need
In the following code I used X object. Replace the X by Y for the other case
object instanceof X; // == true
object.constructor.name; // == "X"
X.prototype.isPrototypeOf(object); // == true