开发者

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[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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜