0

In the following code, .refresh could call .add, but I get Uncaught TypeError: undefined is not a function My guess is because it is not defined at the time class is created, but if this is true, without replicating the code, is there a way to call a sibling public function from the same class?

var fileSelector = (function () {
    var self = this;
    function callback (data,status,xhr) {
        $("#File_Selector_Container").html(data);
        utils.setItem ("fileSelector", "TRUE");
    }
    return {
        refresh : function () {
            if (utils.getItem ("fileSelector") == "TRUE") {
                self.add();
            }
        },
        add : function () {
            $.get(script_name ,"AddFileSelector",callback,"html");
        },
        remove : function () {
            $("#File_Selector_Container").html("");
        }
    }
})();

I started this from: Simplest/Cleanest way to implement singleton in JavaScript? and I can't find it now, but another question where I got self=this from.

Community
  • 1
  • 1
Quade2002
  • 615
  • 2
  • 7
  • 23
  • 1
    `this` (and hence `self`) simply refers to the global object (i.e. `window`). That's why you get the error, there is no global `add` function. I recommend to read the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) to learn how `this` works. – Felix Kling Mar 02 '15 at 23:12
  • this.add() did work, however, looking at the 2nd suggestion....... – Quade2002 Mar 02 '15 at 23:19

1 Answers1

1

this (and hence self) simply refers to the global object (i.e. window). That's why you get the error, there is no global add function. I recommend to read the MDN documentation to learn how this works.

One solution is to keep a reference to the object you are returning and use that instead:

var fileSelector = (function () {
    function callback (data,status,xhr) {
        $("#File_Selector_Container").html(data);
        utils.setItem ("fileSelector", "TRUE");
    }
    var fileSelector = {
        refresh : function () {
            if (utils.getItem ("fileSelector") == "TRUE") {
                fileSelector.add();
            }
        },
        add : function () {
            $.get(script_name ,"AddFileSelector",callback,"html");
        },
        remove : function () {
            $("#File_Selector_Container").html("");
        }
    };

    return fileSelector;
})();
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Worked like a charm, and I like this much better, it is so much easier to follow what is where, Thanks!! – Quade2002 Mar 02 '15 at 23:24