如何在javascript中访问子类内的父类方法

时间:2014-02-24 23:07:01

标签: javascript

我有一个'model'类/原型定义如下,它有一个名为'given'的子类,它试图访问模型类的方法'getNodes()'。

但它给出了'this.getNodes'说明未定义的例外。

 var model = {
        constructor: function(/*string*/ mode, /*string*/ name, /*object*/ properties) {
            this._mode = mode;
            this.beginX = 100;
            this.beginY = 100;
            this.nodeWidth = 200;
            this.nodeHeight = 200;
            this.x = this.beginX;
            this.y = this.beginY;
            this.lastNodeVisible = null;
            this.ID = 1;
            this.taskName = name;
            this.properties = properties;
            this.checkedNodes = new Array();
      //      this.model = #call_build_method;

            /* 
             add subclasses with model accessors 
             */
            this.given = {
            getNodes: this.getNodes,
            setNodeName: this.setNodeName
        };
      },
      getNodes: function() {
            // Summary: returns an array containing the nodes in the given model 
            return #someobject;
        },
}

2 个答案:

答案 0 :(得分:1)

我假设您要在父类中调用具有正确范围的方法。 这有两种方法,一种使用dojo hitch,另一种不使用:

require([
    "dojo/_base/lang"
],function(lang){
    model = function(){
        var obj = {
            data: "ok",
            getData4: function(){
                return this.data;
            }  
        };

        obj.sub = {
            getData5: lang.hitch(obj, obj.getData4),
            getData6: function(){return obj.getData4.apply(obj,arguments);}
        };

        return obj;
    };

    m = new model();
    console.log("call getData4: ", m.getData4());  // returns "ok"
    console.log("call getData5: ", m.sub.getData5());  // returns "ok"
    console.log("call getData6: ", m.sub.getData6());  // returns "ok"
});

答案 1 :(得分:0)

您需要将其存储在外部范围的变量中:

this.model = <SOMETHING>;
var self = this;
this.given = {
    getNodes: function(){self.getNodes(self.model);}
    // inside a function this is this.given
};