假设我需要声明一些private static 成员以便在一些public static 方法中使用它。 .
// ***** Variant I *****
function supports() {
var impl = document.implementation; // private, non-static
this.SVG = function () { // public, non-static
return impl.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
};
}
// ***** Variant II *****
function supports() { }
supports.prototype.impl = document.implementation; // public, non-static
supports.SVG = function () { // public, static
return impl.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
};
我知道在 JavaScript 中使用“静态”OOP 概念存在一些困难,所以我的问题是:
我可以在“对象”的“声明主体”中声明public static方法吗(如上面的“变体 I” )?
最佳答案
JavaScript 中没有私有(private)的、静态的或公共(public)的。只有局部和全局,范围内和范围外。使用 IIFE 捕获变量并返回闭包;这应该等同于静态方法。
var supports = (function supportsWrapper() {
var impl = document.implementation; // "static"-ish.
return function supports() {
this.SVG = function () {
return impl.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
};
}
})();
impl
将仅初始化一次,并且只能由 supports
读取,但会在调用它的过程中持续存在。
关于javascript - 在 JavaScript 类中声明一个公共(public) "static"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649242/