Javascript 具有重复类名的Javasctipt类模式
我想用javascript模拟类,并提出了这个方案Javascript 具有重复类名的Javasctipt类模式,javascript,Javascript,我想用javascript模拟类,并提出了这个方案 var Random = function(a){ // class name used here var Random = function(a){ // and used again here this.valueOf = function(){ return Math.random() } this.under = function(limit){
var Random = function(a){ // class name used here
var Random = function(a){ // and used again here
this.valueOf = function(){
return Math.random()
}
this.under = function(limit){
return this*limit
}
this.floor = function(limit){
return Math.floor(this*limit)
}
}
return new Random(a)
}
var rnd = Random()
console.log(rnd*20<<0)
var Random=函数(a){//此处使用的类名
var Random=函数(a){//并在此处再次使用
this.valueOf=函数(){
return Math.random()
}
this.under=功能(限制){
返回此*限制
}
this.floor=功能(限制){
返回数学楼层(此*限制)
}
}
返回新随机数(a)
}
var rnd=Random()
console.log(rnd*20这是一种非常低效的模式,因为它在每次调用时都会创建一个新的构造函数,而且它没有利用原型继承。此外,仅依靠资本化来表示构造函数不适合维护。至少在new Foo()
中,很明显返回了一个新实例
如果您不喜欢使用new
(我不明白为什么),那么在调用函数中用一个名称包装构造函数,该名称指示构造函数的功能,如newRandom
或类似的功能
关于代码,我不知道为什么使用函数表达式而不是声明。内部函数不需要使用与外部函数相同的名称,事实上内部函数根本不需要名称:
function X(name) {
return new (function(name) {
this.name = name;
})(name)
}
var a = X('a');
a.name; // a
但我不是建议你这么做。有很多JS类库,其中一些支持类派生和基类访问。所有这些都是好的多态性。不要在这里重复发明轮子。我只需要两分钱。我真的不想要一个库,我想要一个我可以记住的模式,并且可以在任何地方使用。我建议大家阅读of:作为可重用的模式。