AP257
AP257

Reputation: 94013

Determining the type of an object in JavaScript

I have a mystery object in Javascript - please could someone tell me how to initialise a similar object?

Background: I've inherited some code that gets passed a params object from Flash. I want to 'fake' the same call, which requires manually constructing the same object. But I can't work out how to take it, because I don't know what type of object it is. (It's not the content that's the problem: it's how to initialise the object.)

Please could someone tell me whether the params object following is an array, a list, a hash or something else - or at least how I can work it out for myself, given that there is no typeof in JavaScript?

function doSomething(params) {
    var txt;
    for (p in params) {
       txt = txt + "param:" + p + ", " + params[p] + "\n";
    }
    return txt;
}

Thanks!

Upvotes: 0

Views: 5925

Answers (4)

Ryan Kinal
Ryan Kinal

Reputation: 17732

There are no lists, hashes, dictionaries (etc.) in JavaScript. There are only objects and arrays (and arrays are a type of object).

Given that the code uses for... in, it looks like it would be an Object. That is, a container with named members. Beyond that, it depends on how the object was initialized.

If you would like to make a copy of the object, try using its prototype:

var copy = {};
copy.prototype = params

Upvotes: 0

Lekensteyn
Lekensteyn

Reputation: 66535

This will alert the type of 'params'.

function doSomething(params) {
    alert("Type of params variable: " + typeof params);
    var txt = '', p;
    for (p in params) {
       txt += "param:" + p + ", " + params[p] + "\n";
    }
    return txt;
}

If you just want to intercept the variable, and pass the param to the original function, try this:

window.originalFunction = doSomething;
window.doSomething = function(param1){
   // do something with param1
   return window.originalFunction(param1);
};

To check whether params is an array or not, try:

alert(params instanceof Array);

Upvotes: 1

Rahul
Rahul

Reputation: 1876

From the looks of it, params looks like a dictionary

Upvotes: 0

Robusto
Robusto

Reputation: 31913

You can think of it as a hash. In your example, p is the property name and params[p] accesses the value of that named property.

And, as usual, Pekka is right. There most definitely is a "typeof" operator in Javascript. I don't know where you got the idea that there isn't.

Upvotes: 0

Related Questions