1

I have an object called Grid and I use new in order to create instances of it. I would like to be able to call its methods from the outside.

This is the (simplified) object:

var Grid = function() {
    this.table = createTable();

    function createTable() {
        // ...
    };

    function setSelectedLine(line) { // this one should be public
        // ...
    };
};

var g = new Grid();
g.setSelectedLine(anyLine); // TypeError: g.setSelectedLine is not a function

I've found other topics with similar questions, but they use very different object constructions. Is it possible to make that method public without having to rewrite everything? The real object is actually bigger than that.

rlemon
  • 17,518
  • 14
  • 92
  • 123
Carcamano
  • 1,153
  • 2
  • 11
  • 24
  • 1
    You can put the methods on the prototype. – elclanrs Aug 18 '15 at 14:01
  • 1
    `this.publicMethod = function () {...};` in a constructor function creates a public own method to every instance created by using that constructor. – Teemu Aug 18 '15 at 14:01
  • 1
    Or `this.setSelectedLine = setSelectedLine;` (but yes, putting them on the prototype is probably better) – Paul S. Aug 18 '15 at 14:02
  • 1
    http://javascript.crockford.com/private.html (misleading name) – Alex K. Aug 18 '15 at 14:02
  • Thanks. I had tried that before, but now I realise the problem happens when I pass the `Grid` object using `self.port.emit("event", gridObj);` (it's a Firefox extension). Looks like the object received isn't the same I sent. I'll have to study more about extension development. – Carcamano Aug 18 '15 at 14:20
  • Ok, reading more about [port](https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/port#json_serializable), I found out that value passed has to be JSON-serialised, which means functions can't be passed. I'll have to find another way. – Carcamano Aug 18 '15 at 14:26

1 Answers1

9

you can add it to the objects prototype:

var Grid = function() { .. };
Grid.prototype.methodName = function() { .. };

or you can add it as a property in the constructor.

var Grid = function() {
  this.methodName = function() { .. };
};

Please note the difference between the two methods

Community
  • 1
  • 1
K-9
  • 110
  • 5