Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"key in obj" when obj is a function?

Tags:

javascript

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?

like image 491
Codier Avatar asked Aug 26 '26 23:08

Codier


2 Answers

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
  }
}
like image 142
RobG Avatar answered Aug 29 '26 12:08

RobG


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).

like image 44
Tikhon Jelvis Avatar answered Aug 29 '26 14:08

Tikhon Jelvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!