0

我需要知道原型类是否理解方法。例如:

MyClass.prototype.myMethod1 = function() {
    ...
    return "Hello World!";
};

MyClass.prototype.myMethod2 = function() {
    ...
    return "Bye World!";
};

MyClass.prototype.caller = function(functionName){ //This is the method that I need to know
    if (functionName == "myMethod1") return "Exist!, is myMethod1.";
    if (functionName == "myMethod2") return "Exist!, is myMethod2.";
    return "Sorry, it doesn't exists here.";
}

这只是一个糟糕的例子。我需要确定MyClass是否不理解该方法,并在这种情况下委托它。

谢谢!

4

2 回答 2

0

可以使用以下方法迭代 MyClass 原型中的每个方法和属性:

MyClass.prototype.hasMethod = function(name) {
  for (key in this) {
    if (key == name) 
      return true;
    }
    return false;
}
于 2013-10-09T13:15:51.223 回答
0

这不是问题的实际答案。问题已在评论中解决。这个问题没有实际答案,因为 Javascript 没有神奇的方法。

所以需要检查对象是否有一定的方法?我想这就是你要找的:

MyClass.prototype.caller = function(functionName) {
    // Check whether the property is a function
    if (typeof(this[functionName]) == "function") {
        // Method exists
        return true;
    } else {
        // Method does not exist
        return false;
    }
};
于 2013-10-09T13:11:34.307 回答