1

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

Don Jose
  • 1,448
  • 2
  • 13
  • 27

2 Answers2

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • 2
    See comments in my answer about `object.constructor.name`. It isn't reliable (people mess up `constructor` all the time), and doesn't officially exist at all in ES5 and earlier. – T.J. Crowder Sep 12 '16 at 06:31
  • When would you use `X.prototype.isPrototypeOf(object)` rather than `object instanceof X`? – nnnnnn Sep 12 '16 at 06:36
  • 1
    Yes, my point was that that information should be directly in the answer. – nnnnnn Sep 12 '16 at 06:47
  • I should clarify my comment above: People mess up `constructor` all the time, and `name` on functions doesn't officially exist at all in ES5 and earlier (`constructor` does!). – T.J. Crowder Sep 12 '16 at 06:49