在静态方法之间共享代码

时间:2014-05-04 22:06:40

标签: javascript

是否可以在Javascript静态方法之间共享代码,而无需公开共享方法?

例如:

// public method
Company.getByUri = function(uri)
{
  // ...
  return gotCompany(data);
}

// public method
Company.getByName = function(name)
{
  // ...
  return gotCompany(data);
}

// Should be a private method, but I'm forced to keep it public
Company.gotCompany = function(data)
{
  // ...
  return new Company(data.name, data.creationDate);
}

1 个答案:

答案 0 :(得分:1)

您可以使用闭包:

var Company = (function() {
    function Company(a, b) { /* ... */ }
    Company.getByUri = function(uri) {  return gotCompany(data); }
    Company.getByName = function(name) {  return gotCompany(data); }
    function gotCompany(data) {
        return new Company(data.name, data.creationDate);
    }
    return Company;
})();
// Here `Company.getByUri` and `Company.getByName` are available,
// but not `gotCompany`