Javascript 如何判断一个javascript变量是否是一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5861763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to tell if a javascript variable is a function
提问by Mr Bell
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?
我需要遍历 javascript 对象的属性。如何判断一个属性是一个函数还是一个值?
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];
}
回答by Phrogz
Use the typeof
operator:
使用typeof
运算符:
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;
...
}
回答by Kashyap
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
回答by Rintala
You can use the following solution to check if a JavaScript variable is a function:
您可以使用以下解决方案来检查 JavaScript 变量是否为函数:
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];
}