Javascript 检查对象是否具有使用字符串变量定义的函数
给定以下代码,我想使用变量Javascript 检查对象是否具有使用字符串变量定义的函数,javascript,Javascript,给定以下代码,我想使用变量fn检查someObject是否具有bar函数 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
fn
检查someObject
是否具有bar
函数
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();
this[fn]()代码>+fn在这种类型的[fn]
@Subash-怎么会这样?我刚试过。很好用。与其说它错了,不如解释它的错在哪里。我满足了你提出的要求。如果这是不正确的,你应该解决这个问题。
if (typeof this[fn] === 'function') {
this[fn]();
}