【问题标题】:How to make a method public in JavaScript如何在 JavaScript 中公开方法
【发布时间】:2015-11-11 12:25:45
【问题描述】:

我有一个名为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

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

【问题讨论】:

  • 你可以把方法放在原型上。
  • this.publicMethod = function () {...}; 在构造函数中为使用该构造函数创建的每个实例创建一个自己的公共方法。
  • this.setSelectedLine = setSelectedLine;(但是,将它们放在原型上可能会更好)
  • 谢谢。我之前曾尝试过,但现在我意识到当我使用self.port.emit("event", gridObj);(它是一个Firefox 扩展)传递Grid 对象时会出现问题。看起来收到的对象与我发送的对象不同。我将不得不学习更多关于扩展开发的知识。

标签: javascript methods visibility


【解决方案1】:

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

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

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

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

请注意difference between the two methods

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多