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]; }
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.
A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.
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.
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; ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With