Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return objects interface name/type?

Tags:

javascript

Is there a function or something to get the interface of an object?

Like, for <p/> = HTMLParagraphElement, how would I retrieve it?

Thanks in advance!

like image 325
tomsseisums Avatar asked Dec 17 '22 09:12

tomsseisums


2 Answers

I think there are just one way to do so: fetch a list of all available interfaces, iterate via this list and check your variable value for type using instanceof operator.

This way should work like following:

var element = ... // here your element comes
var interfaces = [HTMLParagraphElement, HTMLDivElement];
var interface = interfaces.filter(function (x) { return element instanceof x; })[0].toString();

Now you get something like function HTMLParagraphElement() { [native code] } in interface variable (if element is <p />). I assume this only works for V8 (Google Chrome). Now you can use regexies to extract interface name.

interface.match(/function (.+)\(\)/)[0]

To get list of all interfaces you can use following (works only for HTML elements):

var interfaces = [];
for (var key in window) {
  if (key.indexOf('HTML') == 0)
    interfaces.push(window[key]);
}

I agree with duri's answer, so you don't need to enumerate all interfaces, using of constructor method is more easy way to get prototype function. After that you can use regex I wrote to extract interface name.

like image 71
Eskat0n Avatar answered Dec 21 '22 22:12

Eskat0n


Just use document.createElement('p').constructor, this returns the HTMLParagraphElement object.

If you want to get just the name of the interface (as a string), call toString() method on the object (you'll get result similar to [object InterfaceName]) and parse it using some string methods (e.g. regular expressions): document.createElement('p').toString().match(/^\[object (.*)\]$/)[1].

like image 35
duri Avatar answered Dec 21 '22 22:12

duri