代码之家  ›  专栏  ›  技术社区  ›  Zoidberg

javascript中的超类方法

  •  2
  • Zoidberg  · 技术社区  · 16 年前

    我正在用javascript编写一些对象(我猜是类)。类B继承自类A。类A有一个名为isValid的方法,类B重写该方法。我使用YUI扩展函数让B类扩展A类。

    A = function(){
    }
    A.prototype = {
       isValid:function(){
           /* Some logic */
           return booleanValue;
       }
    }
    
    B = function(){
    }
    
    YAHOO.lang.extend(B, A,{
         isValid:function(){
            // call class A's valid function
            // some more logic for class B.
            return booleanValue;
         }
    });
    

    我希望能够在类B的isValid函数中调用类A的isValid函数。问题是,我可以从类B的isValid方法访问类A的isValid方法吗?我知道您可以通过下面的行从类B的构造函数内部访问类A的构造函数

    this.constructor.superclass.constructor.call(this,someParam);
    

    方法是否也可能类似?如果没有,什么是这样做的良好实践?目前,我正在创建一个在超类“isValid方法”内部调用的助手方法

    A.prototype = {
        a_isValid:function(){
           // class A's is valid logic
           return booelanValue;
        },
        isValid:function() {return this.a_isValid();}
    }
    

    然后我可以从类B中调用a_isValid函数。这对我来说是可行的,但如果可能的话,我更愿意直接调用超类的isValid函数。

    2 回复  |  直到 13 年前
        1
  •  2
  •   wtaniguchi    16 年前

    来自YUI文档:

    YAHOO.lang.extend(YAHOO.test.Class2, YAHOO.test.Class1); 
    YAHOO.test.Class2.prototype.testMethod = function(info) { 
    // chain the method 
    YAHOO.test.Class2.superclass.testMethod.call(this, info); 
    alert("Class2: " + info); 
    }; 
    

    这对你不管用吗?第4行应该调用Class1的(超类)testMethod。

        2
  •  0
  •   Freeman    13 年前

    我发布了另一种方法,用于文档编制。

    messageFormController 起源于 formController ,你打电话 super.setView 作为:

    messageFormController.setView = function setView(element) {
        formController.setView.bind(this)(element);
        // Additional stuff
    };
    
    推荐文章