我有一个javascript类,一个对象正在传递给它,该对象是匿名的且已更改。我想检查该对象的属性中是否在该类中有匹配的方法名称。

这是使代码清楚的代码:



var Panel = function(obj) {
  for (var prop in obj) {
    if (typeOf this[prop] == function) {   // ?? please help with this check
      this[prop](obj[prop]); // call this method with right argument in this case will be this.maxWidth("400px")
    }
  }

  this.maxWidth = function(max_width) {
    document.getElementById(obj["id"]).style.maxWidth = max_width;
  }
}


var myObj = {
  "maxWidth": "400px"
}

var p = new Panel(myObj);

最佳答案

这是更正后的代码,您需要使用typeof而不是typeOf,并且function需要用引号引起来,因为typeof返回一个字符串:

var Panel = function(obj) {
  for (var prop in obj) {
    if (typeof this[prop] == 'function') {   // ?? please help with this check
      this[prop](obj[prop]); // call this method with right argument in this case will be this.maxWidth("400px")
    }
  }

  this.maxWidth = function(max_width) {
    document.getElementById(obj.id).style.maxWidth = max_width;
  };
};


var myObj = {
  "maxWidth": "400px"
};

var p = new Panel(myObj);


https://jsbin.com/yemoki/1/edit?js,console

10-05 21:07
查看更多