4

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();
1
  • this[fn](); + fn in this + typeof this[fn] Commented Jan 19, 2016 at 5:17

1 Answer 1

3
if (typeof this[fn] === 'function') {
    this[fn]();
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Subash - how so? I just tried it. works just fine. instead of saying it's wrong, explain what is wrong about it. I satisfied the requirements you gave. If that is incorrect, you should address that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.