簡體   English   中英

Javascript:如何攔截Class的所有原型函數?

[英]Javascript: How to intercept all prototype functions of a Class?

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

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是否不理解該方法,並在這種情況下委托它。

謝謝!

這不是該問題的實際答案。 該問題已在評論中得到解決。 這個問題沒有實際答案,因為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;
    }
};

可以使用以下方法遍歷MyClass原型中的每個方法和屬性:

MyClass.prototype.hasMethod = function(name) {
  for (key in this) {
    if (key == name) 
      return true;
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM