如何在 JavaScript 中创建方法 public

How to make a method public in JavaScript

我有一个名为 Grid 的对象,我使用 new 来创建它的实例。我希望能够从外部调用它的方法。

这是(简化的)对象:

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

我发现其他主题也有类似的问题,但它们使用非常不同的对象结构。是否可以使该方法 public 而不必重写所有内容?实物比那个大

您可以将其添加到对象原型中:

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

或者您可以将其作为 属性 添加到构造函数中。

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

请注意difference between the two methods