Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tell if a javascript variable is a function

I need to loop over the properties of a javascript object. How can I tell if a property is a function or just a value?

var model = {     propertyA: 123,     propertyB: function () { return 456; } };  for (var property in model) {     var value;     if(model[property] is function) //how can I tell if it is a function???         value = model[property]();     else          value = model[property]; } 
like image 772
Mr Bell Avatar asked May 02 '11 19:05

Mr Bell


People also ask

How do you check if it is a function?

Determining whether a relation is a function on a graph is relatively easy by using the vertical line test. If a vertical line crosses the relation on the graph only once in all locations, the relation is a function. However, if a vertical line crosses the relation more than once, the relation is not a function.

What is the difference between a function and a variable in JavaScript?

A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.

What is function () () in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.


1 Answers

Use the typeof operator:

if (typeof model[property] == 'function') ... 

Also, note that you should be sure that the properties you are iterating are part of this object, and not inherited as a public property on the prototype of some other object up the inheritance chain:

for (var property in model){   if (!model.hasOwnProperty(property)) continue;   ... } 
like image 154
Phrogz Avatar answered Sep 26 '22 22:09

Phrogz