I am very new to JavaScript, so I am baffled by the following syntax:
if (isFunction(obj)){
for (key in obj) {
//do something
}
}
The isFunction method will return true if typeOf obj=="function". But what happens when you it says key in obj when obj is a function?
The for..in loop iterates over the enumerable properties of obj. Functions are objects, they have their own properties plus inherited properties from their [[prototype]] chain. See ECMA-262 §12.6.4.
Also, don't forget to declare variables that should be kept local.
To address only the enumerable properties on obj and not its inherited enumerable properties, it is usual to include a hasOwnProperty test:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// key is enumerable property of obj, not inherited
}
}
JavaScript functions are also objects, which means they can have properties. You can do something like this:
var f = function () {};
f.a = "foo";
f.b = "bar";
If obj was f, then the for loop would iterate with key being "a" and "b".
Basically, the for in loop iterates over all of the properties of an object except those internally marked as non-enumerable (mostly built-in methods and properties).
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