最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to make a method public in JavaScript - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Aug 19, 2015 at 23:55 rlemon 17.7k14 gold badges94 silver badges126 bronze badges asked Aug 18, 2015 at 14:00 CarcamanoCarcamano 1,1732 gold badges11 silver badges24 bronze badges 6
  • 1 You can put the methods on the prototype. – elclanrs Commented Aug 18, 2015 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 Commented Aug 18, 2015 at 14:01
  • 1 Or this.setSelectedLine = setSelectedLine; (but yes, putting them on the prototype is probably better) – Paul S. Commented Aug 18, 2015 at 14:02
  • 1 javascript.crockford./private.html (misleading name) – Alex K. Commented Aug 18, 2015 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 Commented Aug 18, 2015 at 14:20
 |  Show 1 more ment

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论