gpt4 book ai didi

javascript - 在静态方法之间共享代码

转载 作者:行者123 更新时间:2023-12-03 12:42:58 25 4
gpt4 key购买 nike

是否可以在 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);
}

最佳答案

您可以使用闭包:

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`

关于javascript - 在静态方法之间共享代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com