简体   繁体   English

当 obj 是 function 时,“key in obj”?

[英]“key in obj” when obj is a function?

I am very new to JavaScript, so I am baffled by the following syntax:我对 JavaScript 很陌生,所以我对以下语法感到困惑:

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

The isFunction method will return true if typeOf obj=="function" .如果typeOf obj=="function"isFunction方法将返回 true 。 But what happens when you it says key in obj when obj is a function?但是当obj是 function 时,当你说key in obj时会发生什么?

JavaScript functions are also objects, which means they can have properties. JavaScript 函数也是对象,这意味着它们可以具有属性。 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" .如果objf ,那么for循环将迭代key"a""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).基本上, for in循环遍历 object 的所有属性,除了那些在内部标记为不可枚举的属性(主要是内置方法和属性)。

The for..in loop iterates over the enumerable properties of obj . for..in循环遍历obj的可枚举属性。 Functions are objects, they have their own properties plus inherited properties from their [[prototype]] chain.函数是对象,它们有自己的属性以及从它们的 [[prototype]] 链继承的属性。 See ECMA-262 §12.6.4.参见 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:为了只处理obj上的可枚举属性而不是其继承的可枚举属性,通常包含一个hasOwnProperty测试:

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

Functions can also have properties, - the following code is valid:函数也可以有属性,- 下面的代码是有效的:

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

the for (key in obj) loop would enumerate prop1 and prop2. for (key in obj)循环将枚举 prop1 和 prop2。

Here's a jsfiddle (not sure if this helps) http://jsfiddle.net/FEAzV/这是一个jsfiddle(不确定这是否有帮助) http://jsfiddle.net/FEAzV/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM