在javascript中将全局函数转换为静态实用程序
我有一个形状类,它在全局范围内定义:在javascript中将全局函数转换为静态实用程序,javascript,Javascript,我有一个形状类,它在全局范围内定义: function Shape(t) { this.type; Shape.prototype.init = function(){ this.type = t; //more work here } this.init(); } 我希望将所有全
function Shape(t) {
this.type;
Shape.prototype.init = function(){
this.type = t;
//more work here
}
this.init();
}
我希望将所有全局函数/类合并到一个类中,以避免与全局命名空间冲突
function Util(){}
Util.Shape = function(){...}
Util.Point = function(){...}
这是可行的,但我不喜欢每次都重复Util.
,所以我为相关函数使用类似命名空间的属性,在本例中为math:
Util.math = {
Shape: function(t) {
this.type;
Shape.prototype.init = function(){
this.type = t;
//more work here
}
this.init();
},
Point: function(t) {...}
}
但这不起作用;抱怨这个.init()
;有意义,因为形状。此处不需要原型,因此将其删除:
Util.math = {
Shape: function(t) {
this.type;
this.init = function(){
this.type = t;
}
this.init();
}
}
现在工作:
var square = new Util.math.Shape('square');
var circle = new Util.math.Shape('circle');
console.log(square.type); // 'square'
console.log(circle.type); // 'circle'
问题:
这种方法有什么问题吗?更有效/更清洁的方法?
还有,为什么这不起作用?(这是)
Util.math={
形状:函数(t){
这种类型;
this.init=函数(){
this.type=t;
}
}.init();//您还可以执行以下操作:
var myLib = (function() {
var obj = {};
function Shape(t) {
this.init(t);
}
Shape.prototype.init = function(t){
this.type = t;
}
obj.Shape = Shape;
// more stuff
return obj;
}());
var shape = new myLib.Shape('circle');
console.log(shape.type); // circle
假设init只是一个例子。但这不起作用;抱怨这个。init()
因为函数表达式不同于函数声明。有意义,因为这里不需要Shape.prototype
-如果“这里不需要”我相信你是正确的,有趣的,所以obj就像一个类型商店?是的,看看真实是如何组合起来的。
var myLib = (function() {
var obj = {};
function Shape(t) {
this.init(t);
}
Shape.prototype.init = function(t){
this.type = t;
}
obj.Shape = Shape;
// more stuff
return obj;
}());
var shape = new myLib.Shape('circle');
console.log(shape.type); // circle