问题描述
我知道,这经常被讨论.但在像 19 世纪的人一样四处寻找之后,我需要一些建议.声明命名空间"没有问题,但是当涉及到prototype.foo 函数时,我卡住了.我找到了一种方法,但我不喜欢它:
I know, this is often discussed. But after searching around like someone out of the 19th century, I need some advice. I have no problem by declaring a "namespace", but when it comes to a prototype.foo function, I stuck. I found a way, but I don't like it:
Namespace = {}
Namespace.obj = function() {
this.foo="bar";
}
Namespace.obj.prototype.start = function() {
this.foo="fubar";
}
blah = new Namespace.obj();
blah.start();
现在,由于我在编写脚本时有点神经质,所以我想要这样的东西:
Now, since I'm a little neurotic in case of scripting, I would like to have something like this:
Namespace = {
obj: function() {
this.foo="bar";
},
obj.prototype.start: function(tabinst) {
this.foo="fubar";
}
}
...
但随后会引发错误:"Uncaught SyntaxError: Unexpected token ."
But then it throws an error: "Uncaught SyntaxError: Unexpected token ."
我知道,这是装饰性的,但我认为必须有更好的方法来声明包含类和原型函数的命名空间".
I know, this is cosmetic, but I think that there has to be a better method of declaring a "namespace" containing a class and prototype functions.
推荐答案
我的做法是使用 "模块模式".
您基本上将所有模块"逻辑封装在一个自执行函数中,该函数将返回一个具有您的类、函数、变量等的对象......将返回值视为公开您的模块 API.
The way I would do it is using the "Module pattern".
You basically encapsulate all your "Module" logic in a self executing function that would return an object having your classes, functions, variables etc... Think of the return value as exposing your Module API.
Namespace = (function () {
/** Class obj **/
var obj = function () {
this.foo = 'bar';
};
obj.prototype = {
start: function () {
this.foo = 'fubar';
}
};
/** Class obj2 **/
var obj2 = function () {
this.bar = 'foo'
};
obj2.prototype = {
start: function () {
this.bar = 'barfoo';
},
end: function () {
this.bar = '';
}
};
return {
obj : obj,
obj2: obj2
};
})();
var o = new Namespace.obj()
o.start()
为了进一步封装obj"类的方法和构造函数,我们可以这样做:
In order to further encapsulate the "obj" class methods and constructor we could do the following:
/** Class obj **/
var obj = (function () {
/** class Constructor **/
var obj = function () {
this.foo = 'bar';
};
/** class methods **/
obj.prototype = {
start: function () {
this.foo = 'fubar';
}
};
return obj;
})();
使用此模式还有一个免费的重要功能,即私有变量",请考虑以下几点:
There is also an important feature that comes for free using this pattern, which is "Private variables", consider the following:
/** Class Foo **/
var Foo = (function () {
// Private variables
var private_number = 200
/** class Constructor **/
var Foo = function () {
this.bar = 0;
};
/** class methods **/
Foo.prototype = {
add: function () {
this.bar += private_number;
}
};
return Foo;
})();
foo = new Foo();
alert(foo.bar); // 0
foo.add();
alert(foo.bar);// 200
alert(foo.private_number) //undefined
这篇关于带有函数原型的 Javascript 命名空间声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!