简体   繁体   English

调用文字对象中的每个函数(Javascript)

[英]Call each function in a literal object (Javascript)

How can I call each function in this object? 如何调用此对象中的每个函数?

var obj = {
  hey1: function() {
    alert('hey');
  },
  hey2: function() {
    alert('hey2');
  },
  hey3: function() {
    alert('hey3');
  }
}

I'd like each function to run one after the other. 我希望每个函数都能一个接一个地运行。 I'm looking for something like: 我正在寻找类似的东西:

for (var hey in obj) {
  hey();
}

But obviously that doesn't run (otherwise I wouldn't be asking this question). 但显然不会运行(否则我不会问这个问题)。

Thanks guys!!! 多谢你们!!!

for (var hey in obj) {
    obj[hey]();
}

In a situation where it is not guaranteed that each property will be a function, you can weed out other properties: 在无法保证每个属性都是函数的情况下,您可以清除其他属性:

for (var hey in obj) {
    if (typeof obj[hey] == "function") {
        obj[hey]();
    }
}

To further restrict it to only immediate properties of the object (and not the ones inherited from its prototype): 进一步将其限制为仅对象的直接属性(而不是从其原型继承的属性):

for (var hey in obj) {
    if (typeof obj[hey] == "function" && obj.hasOwnProperty(hey)) {
        obj[hey]();
    }
}

Lopping will give you they keys, not the values. Lopping会给你他们的钥匙,而不是价值。 Use the key to get the value: 使用键获取值:

for (var hey in obj) {
  obj[hey]();
}

jsfiddle.net/s8tbr/ jsfiddle.net/s8tbr/

Note: Depending on from where you get the object, you might want to check that the properties are members of the object itself, not inherited from a prototype: 注意:根据获取对象的位置,您可能希望检查属性是对象本身的成员,而不是从原型继承:

for (var hey in obj) {
  if (obj.hasOwnProperty(hey)) {
    obj[hey]();
  }
}

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

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