Javascript动态函数调用

Ste*_*oss 1 javascript dynamic

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

ele.style.backgroundColor = someSetting
ele.style.padding = anotherSetting
Run Code Online (Sandbox Code Playgroud)

我想做什么(我将用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'
Run Code Online (Sandbox Code Playgroud)

在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'
});
Run Code Online (Sandbox Code Playgroud)

谢谢!

Rob*_*b W 8

使用方括号:

element.style[styleAttribute] = setting
Run Code Online (Sandbox Code Playgroud)

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

window.location.href === window["location"].href === window["location"]["href"]
    === window.location["href"]
Run Code Online (Sandbox Code Playgroud)