如何正确设置JavaScript命名空间和类? [英] How to set up JavaScript namespace and classes properly?
问题描述
似乎有很多方法可以设置JavaScript应用程序,因此令人困惑的是哪一个是正确的还是最好的。以下技术或更好的方法有什么不同吗?
It seems there are so many ways to set up a JavaScript application so it is confusing as to which one is correct or best. Are there any difference to the below techniques or a better way of doing this?
MyNamespace.MyClass = {
someProperty: 5,
anotherProperty: false,
init: function () {
//do initialization
},
someFunction: function () {
//do something
}
};
$(function () {
MyNamespace.MyClass.init();
});
另一种方式:
MyNamespace.MyClass = (function () {
var someProperty = 5;
var anotherProperty = false;
var init = function () {
//do something
};
var someFunction = function () {
//do something
};
return {
someProperty: someProperty
anotherProperty: anotherProperty
init: init
someFunction: someFunction
};
}());
MyNamespace.MyClass.init();
第一种技术感觉更像是一个类。如果这有所不同,我来自服务器端背景。第二种技术似乎更冗余,有点尴尬,但我看到这也使用了很多。有人可以帮助解决一些问题并建议前进的最佳方式吗?我想创建一个有很多类相互交流的应用程序。
The first technique feels more like a class. I am coming from server-side background if this makes a difference. The second technique seems more redundant and a bit awkward, but I see this used a lot too. Can someone please help shed some light and advise the best way to move forward? I want to create a application with lots of classes talking to each other.
推荐答案
不要做这两件事。
制作一个javascriptclass:
Make a javascript "class":
var MyClass = function () {
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
MyNamespace.MyClass = new MyClass();
一个有静态变量:
One with static vars:
var MyClass = (function(){
var static_var; //static private var
var MyClass = function () {
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
return MyClass;
})();
MyNamespace.MyClass = new MyClass();
使用构造函数(所有示例)有一个构造函数,这个只有参数可以使用):
With a "constructor" (all of the examples have a "constructor", this one just has parameters to work with):
var MyClass = function (a, b c) {
//DO SOMETHING WITH a, b, c <--
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
MyNamespace.MyClass = new MyClass(1, 3, 4);
综合以上所有你可以:
MyNamespace.MyClass.someFunction();
但无法做到(来自外部):
MyNamespace.MyClass.privateFn(); //ERROR!
这篇关于如何正确设置JavaScript命名空间和类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!