检查Javascript是否包含某些方法

时间:2016-04-15 22:57:23

标签: javascript oop

我有一个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);

1 个答案:

答案 0 :(得分:1)

以下是更正后的代码,您需要使用typeof而非typeOffunction需要用引号括起来,因为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