0

我一直在将我的程序 JS 函数转换为一个类,现在我想知道何时实例化它。

这是我的课:

MyProject = function() {};

MyProject.prototype.myProperty = "10";

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

} 

这是我的 HTML 页面:

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

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

<body onload="initialize()" >

我的问题是我是在页面加载时初始化它并创建一个如上所示的局部变量还是在 JS 类文件中初始化它?

这是我的 JS 文件:

MyProject = function() {};

MyProject.prototype.myProperty = "10";

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

} 

myProject = new MyProject();

另外,我说的是一般情况,在这种情况下它是一个单例。我只想使用它的一份副本。

4

2 回答 2

3

如果你真的想要它作为一个单例,你可以比这更容易,比如:

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

您的“类”只定义了足够长的时间来分配一次,因为您永远不会实例化第二个副本。

对于非单例,我倾向于遵循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");
于 2013-11-11T23:05:42.357 回答
2

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.

于 2013-11-11T23:31:07.433 回答