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[proper开发者_如何学Pythonty];
}
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;
...
}
Following might be useful to you, I think.
How can I check if a javascript variable is function type?
BTW, I am using following to check for the function.
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
You can use the following solution to check if a JavaScript variable is a function:
var model =
{
propertyA: 123,
propertyB: function () { return 456; }
};
for (var property in model)
{
var value;
if(typeof model[property] == 'function') // Like so!
else
value = model[property];
}
精彩评论