我怎样才能模仿“类”在JavaScript? (有或没有第三方库) [英] How can I emulate "classes" in JavaScript? (with or without a third-party library)

查看:99
本文介绍了我怎样才能模仿“类”在JavaScript? (有或没有第三方库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I emulate classes (and namespaces) in JavaScript?

我需要创建一个JavaScript库,并且对该语言的使用经验有限。我一直认为它对类有本机支持,但它与Java的相关性低于我的假设。似乎JavaScript中的所有内容实际上都是一个函数。

I need to create a JavaScript library and have limited experience with the language. I always thought that it had native support for classes, but it is less related to Java than I had assumed. It seems that everything in JavaScript is actually a function.

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

What I have found out so far makes a lot of sense with it being a dynamic weakly typed language, but this makes it a bit of a departure for people who are used to having a strongly typed language and using a compiler to spot our errors :)

我主要使用C#和Java,并且希望语法类似,所以这个库看起来很熟悉我们需要维护它的其他C#开发人员。

I mainly work in C# and Java, and was hoping for something syntacticaly similar so the library would look familiar for our other C# developers that will have to maintain it.

我有以下类型的代码可以工作,但我想知道其他开发人员会采取什么措施。有哪些替代方案?有没有更好的方法?有没有更可读的方法?

I have the following sort of code which works, but I was wondering what other developer's takes would be on this. What are the alternatives? Is there a way that is better? Is there a way that is more readable?

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

I understand that what I want is something similar to C# or Java when I should just accept the fact that this is JavaScript, but my aim is to try to ease the learning curve for other developers by making it more familiar and intuitive for them.

//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();


推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆