Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object has function defined using a string variable

Tags:

javascript

Given following code, I want to check if someObject has bar function using the variable fn.

var SomeObject = function() {};

SomeObject.prototype.foo = function() {
   var fn = 'bar';

   // todo: I want to check if this object has 'bar' function.
   // if yes call it

   // Note: you can't do if(typeof this.bar === 'function')
   // got to use the variable fn
};

var OtherObject = function() {
    SomeObject.call(this);
};

OtherObject.prototype = Object.create(SomeObject.prototype);

OtherObject.prototype.bar = function() {
    console.log('great. I was just called.');
};

var obj = new OtherObject();
obj.foo();
like image 979
Subash Avatar asked Oct 15 '25 04:10

Subash


1 Answers

if (typeof this[fn] === 'function') {
    this[fn]();
}
like image 97
Antiokus Avatar answered Oct 17 '25 16:10

Antiokus