检查Javascript是否包含某种方法

Check if Javascript contains certain method

本文关键字:方法 包含某 是否 Javascript 检查      更新时间:2023-09-26

我有一个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而不是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,控制台