gpt4 book ai didi

javascript - 如何在 JavaScript 中模拟 "classes"? (有或没有第三方库)

转载 作者:行者123 更新时间:2023-12-02 22:51:07 25 4
gpt4 key购买 nike

如何在 JavaScript 中模拟类(和命名空间)?

我需要创建一个 JavaScript 库,并且对该语言的经验有限。我一直认为它对类有 native 支持,但它与 Java 的相关性比我想象的要少。看来 JavaScript 中的一切实际上都是函数。

到目前为止,我发现它是一种动态弱类型语言,这很有意义,但这对于习惯使用强类型语言并使用编译器来发现的人来说有点背离我们的错误:)

我主要使用 C# 和 Java 进行工作,并且希望有一些语法上相似的东西,这样该库对于我们必须维护它的其他 C# 开发人员来说会看起来很熟悉。

我有以下有效的代码,但我想知道其他开发人员对此有何看法。有哪些替代方案?有没有更好的方法呢?有没有更易读的方法?

我知道我想要的是类似于 C# 或 Java 的东西,而我应该接受这个是 JavaScript 的事实,但我的目标是尝试通过以下方式简化其他开发人员的学习曲线让他们更加熟悉和直观。

//Perform the namespace setup (this will actually be done with checking 
//in real life so we don't overwrite definitions, but this is kept short
//for the code sample).
var DoctaJonez = new function();
DoctaJonez.Namespace1 = new function();

/**
* Class description.
*/
DoctaJonez.Namespace1.SomeClass = function()
{
/**
* Public functions listed at the top to act like a "header".
*/
this.publicFunction = privateFunction;

/**
* Private variables next.
*/
var privateVariable;

/**
* Finally private functions.
*/
function privateFunction()
{

}
}

//Create an instance of the class
var myClass = new DoctaJonez.SomeClass();

//Do some stuff with the instance
myClass.publicFunction();

最佳答案

关于javascript - 如何在 JavaScript 中模拟 "classes"? (有或没有第三方库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/355848/

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