检查对象是否使用字符串变量定义了函数

时间:2016-01-19 05:14:07

标签: javascript

根据以下代码,我想使用变量someObject检查bar是否具有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 个答案:

答案 0 :(得分:2)

if (typeof this[fn] === 'function') {
    this[fn]();
}