0

I have a 'model' class/prototype defined as below, it has subclass named 'given' which tries to access method 'getNodes()' of model class.

But it gives exception for 'this.getNodes' saying undefined.

 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;
        },
}
Pradeep
  • 5,421
  • 8
  • 31
  • 58
  • When you have a function around `this` think twice. `this` depends on how that function gets called. In your case you need to cache it, like `var self=this` in the higher scope. See http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs Feb 24 '14 at 23:08
  • any code sample please – Pradeep Feb 24 '14 at 23:09
  • How do you invoke that constructor? – Bergi Feb 24 '14 at 23:09
  • what does it has to do wih dojo? anyway get a basic understanding of the word this in javascript here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – mpm Feb 24 '14 at 23:10
  • You may find this helpful.http://stackoverflow.com/a/16063711/1641941 – HMR Feb 25 '14 at 05:17

2 Answers2

1

I assume that you want to call a method in the parent class with the correct scope. Here are two ways to do this, one using dojo hitch, and one without:

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"
});
BvdS
  • 86
  • 1
  • 6
0

You need to store this in variable in outter scope:

this.model = <SOMETHING>;
var self = this;
this.given = {
    getNodes: function(){self.getNodes(self.model);}
    // inside a function this is this.given
};
jcubic
  • 51,975
  • 42
  • 183
  • 323