gpt4 book ai didi

javascript - 访问私有(private)静态对象和方法

转载 作者:行者123 更新时间:2023-11-30 12:14:08 28 4
gpt4 key购买 nike

我正在阅读有关在 javascript 中创建对象的最佳方法并找到一个有趣的解决方案 here .

var Foo = function()
{

var privateStaticMethod = function() {};
var privateStaticVariable = "foo";

var constructor = function Foo(foo, bar)
{
var privateMethod = function() {};
this.publicMethod = function() {};
};

constructor.publicStaticMethod = function() {};

return constructor;
}();

我一直在玩这个结构,但我想知道我该如何做一些事情。

  • 如何从 constructor.publicStaticMethod 中访问 privateStaticVariableprivateStaticMethod

  • 如果我创建第二个公共(public)方法,如 constructor.secondPublicStaticMethod = function(){};,我如何从 constructor.publicStaticMethod 中访问它?

  • 如果我要实例化此对象,我如何从 constructor 中访问所有静态属性和方法?

最佳答案

How can I access privateStaticVariable or privateStaticMethod from within constructor.publicStaticMethod

您可以简单地通过使用它们的名称来访问它们,因为它们是 constructor.publicStaticMethod 中的封闭变量,因为 the closure property .

If I create a second public method like constructor.secondPublicStaticMethod = function(){};, how can I access it from within constructor.publicStaticMethod

由于 secondPublicStaticMethod 是在 constructor 对象上定义的函数,您可以像 constructor.secondPublicStaticMethod 一样简单地调用它

If I was to instantiate this object, how could I access all static properties and methods from within constructor

这与上面提到的类似。您只需分别编写 privateStaticVariableprivateStaticMethod 即可访问 privateStaticVariableprivateStaticMethod。定义在 constructor 上的函数可以通过 constructor.publicStaticMethod

访问

关于javascript - 访问私有(private)静态对象和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32886169/

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