2014-02-24 74 views
0

我有一個'model'類/原型定義如下,它有一個名爲'given'的子類,它嘗試訪問模型類的方法'getNodes()'。如何訪問JavaScript中子類中父類的方法

但它給出'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; 
     }, 
} 
+0

當你周圍有一個函數'this'三思而後行。這個'取決於如何調用這個函數。在你的情況下,你需要緩存它,比如'var self = this'在更高的範圍內。請參閱http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs

+0

任何代碼示例請 – Pradeep

+0

如何調用該構造函數? – Bergi

回答

1

我假設你想調用父類的方法與正確的範圍。 這裏有兩種方法可以做到這一點,一個使用Dojo順利,一個沒有:

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" 
}); 
0

你需要在變量這些信息存儲在outter範圍:

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