Mr *_*ell 27 javascript typeof
我需要循环遍历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];
}
Run Code Online (Sandbox Code Playgroud)
Phr*_*ogz 51
使用typeof运营商:
if (typeof model[property] == 'function') ...
Run Code Online (Sandbox Code Playgroud)
另请注意,您应该确保要迭代的属性是此对象的一部分,而不是作为继承链上某些其他对象的原型的公共属性继承:
for (var property in model){
if (!model.hasOwnProperty(property)) continue;
...
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为以下内容可能对您有用。
顺便说一句,我正在使用以下来检查该功能。
// 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
Run Code Online (Sandbox Code Playgroud)