"key in obj" when obj is a function?

I am very new to JavaScript, so the following syntax puzzles me:

if (isFunction(obj)){
  for (key in obj) {
    //do something
  }
 }

The method isFunctionwill return true if typeOf obj=="function". But what happens when you say key in objwhen objis a function?

+3
source share
4 answers

The loop for..initerates over enumerated properties obj. Functions are objects, they have their own properties plus inherited properties from the [[prototype]] chain. See ECMA-262 §12.6.4.

Also, be sure to declare variables that should be stored locally.

To address only enumerated properties in obj, rather than its inherited enumerated properties, usually include the hasOwnProperty test:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    // key is enumerable property of obj, not inherited
  }
}
+4

JavaScript , , . - :

var f = function () {};
f.a = "foo";
f.b = "bar";

obj f, for key "a" "b".

, for in , , ( ).

+4

, - :

var foo = function() { }
foo.prop1 = 1;
foo.prop2 = "hello";

for (key in obj) prop1 prop2.

+1
+1

All Articles