简体   繁体   English

如何在浏览器中使用基于类的OOP JavaScript?

[英]How do you use class based OOP JavaScript in the browser?

I've been converting my procedural JS functions into a class and now I'd like to know when to instantiate it. 我一直在将过程式JS函数转换为一个类,现在我想知道何时实例化它。

Here is my class: 这是我的课:

MyProject = function() {};

MyProject.prototype.myProperty = "10";

MyProject.prototype.myMethod = function (value) {
   // do something

} 

Here is my HTML page: 这是我的HTML页面:

<script src="javascriptfilesdirectory/MyProject.js"/>

<script>
function initialize() {
   myProject = new MyProject();
}
</script>

<body onload="initialize()" >

My question is do I intialize it on page load and create a local variable as shown above or do I initialize it in the JS class file? 我的问题是我是在页面加载时初始化它并创建一个如上所示的局部变量,还是在JS类文件中对其进行初始化?

Here is my JS file: 这是我的JS文件:

MyProject = function() {};

MyProject.prototype.myProperty = "10";

MyProject.prototype.myMethod = function (value) {
   // do something

} 

myProject = new MyProject();

Also, I'm talking in general and in this case it's a singleton. 另外,我一般来说,在这种情况下,这是一个单例。 I only want one copy of it in use. 我只想使用它的一个副本。

If you really want it as a singleton, you can do it easier than that, something like: 如果您确实希望将其作为单例,则可以做到这一点,例如:

var myProject = new (function() {
    this.myProperty = "10";
    this.myMethod = function(value) { }
})();

Your "class" is only defined long enough to assign it once, since you're never going to instantiate a second copy. 您定义的“类”只有足够长的时间才能分配一次,因为您永远不会实例化第二个副本。

For a non-singleton, I tend to follow the pattern found on the TypeScript page: 对于非单例,我倾向于遵循在TypeScript页面上找到的模式:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

var greeter = new Greeter("world");

Also, I'm talking in general and in this case it's a singleton. 另外,我一般来说,在这种情况下,这是一个单例。 I only want one copy of it in use. 我只想使用它的一个副本。

In that case, just directly create the object: 在这种情况下,只需直接创建对象:

var myProject = {
    myProperty: "10",
    myMethod: function() { ... }
};

When and where you create the object doesn't matter, as long as you have access to it when and where you need it. 只要可以在需要的时间和位置访问它,创建对象的时间和位置都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM