Reputation: 21406
The screenshot below shows the highlighted JavaScript object being of type Telerik.Web.UI.Grid
.
Question : What would be the right JavaScript code to get the true type of JavaScript object $telerik.radControls[6]
? I need to dynamically determine the true type at runtime in JavaScript and then do something based on the true type.
I tried the code below, but typeof always returns object
.
if (typeof $telerik.radControls[6] === "Telerik.Web.UI.RadGrid") {
//do something
} else if(typeof $telerik.radControls[6] === "Telerik.Web.UI.RadSearchBox") {
//do something
} else if (typeof $telerik.radControls[6] === "Telerik.Web.UI.RadTreeView") {
//do something
}
UPDATE 1
I tried some suggestions mentioned under comments, but I get not available when I use instanceof
as in screen show below.
UPDATE 2
I found an interesting fact when using instanceof
to determine the true type of a JavaScript object. The code below will not work always. It will only work if there is already an object of type Telerik.Web.UI.RadGrid
i.e. a constructor for the object type we are checking has been called. I got the following error when no object of Telerik.Web.UI.RadGrid
had been instantiated.
Uncaught TypeError: Expecting a function in instanceof check, but got undefined
Unsafe Code that will work only if the object type exists
if (x instance of Telerik.Web.UI.RadGrid) {
//do something
}
However, when I used code like below then it will not throw an error even when no object of Telerik.Web.UI.RaGrid
type has been instantiated.
Safe Code that will always work i.e. not throw an error
if (typeof Telerik.Web.UI.RadGrid !== "undefined && x instance of Telerik.Web.UI.RadGrid) {
//do something
}
Upvotes: 0
Views: 194
Reputation:
The instanceof
operator will give you a boolean result telling you if its left operand, an object, has the .prototype
of the right operand, a function, in its prototype chain.
So assuming Telerik.Web.UI.RadGrid
is the constructor function, you can do this:
$telerik.radControls[6] instanceof Telerik.Web.UI.RadGrid
Upvotes: 3