Joe Saad
Joe Saad

Reputation: 1950

Check if Javascript contains certain method

I'm having a javascript class, that an object is being passed to it, that object is anonymous and changes. I want to check if within the properties of that object there's a matching method name within that class.

Here's code to make it clear:

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);

Upvotes: 1

Views: 55

Answers (1)

omarjmh
omarjmh

Reputation: 13888

Here is the corrected code, you need to use typeof not typeOf and function needs to be wrapped in quotes, as typeof returns a string:

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

Upvotes: 1

Related Questions