Javascript动态函数调用

时间:2011-10-07 20:43:00

标签: javascript dynamic

我想在Javascript中做一些Rubyish。我正在编写一个关于设置DOM元素样式的包装器。这就像(基于每种风格):

ele.style.backgroundColor = someSetting
ele.style.padding = anotherSetting

我想做的事情(我将用Ruby语法来说明)是:

class Element
  def initialize(ele)
    @ele = ele
  end

  def setDOMElementStyle(styleSettings = {})
    styleSettings.each_pair do |styleAttribute, setting|
      @element.style.send(styleAttribute, setting)
  end

  # Other wrapper stuff for elements here
end

element = Element.new document.createElement("div")
element.setDOMElementStyle :width => '60px', :height => '2px', :top => '0px', :left => '0px'

在Javascript中,我可以使用可怕的eval执行此操作,但我想知道是否有更简洁的方法来处理它。这是邪恶的eval

var Element, element;

Element = function() {
  function Element(element) {
    this.element = element;
  }
  Element.prototype.setDOMElementStyle = function(styleSettings) {
    var setting, styleAttribute;

    if (styleSettings == null) {
      styleSettings = {};
    }
    for (setting in styleSettings) {
      styleAttribute = styleSettings[setting];
      eval("@element.style." + styleAttribute + " = " + setting);
    }
  }
}

element = new Element(document.createElement("div"));
element.setDOMElementStyle({
  width: '60px',
  height: '2px',
  top: '0px',
  left: '0px'
});

谢谢!

1 个答案:

答案 0 :(得分:8)

使用方括号:

element.style[styleAttribute] = setting

在JavaScript中,每个属性也可以通过方括号引用。例子:

window.location.href === window["location"].href === window["location"]["href"]
    === window.location["href"]