Javascript:嵌套(内部)类型的首选设计是什么?
我对构造函数使用Resig的makeClass()方法:Javascript:嵌套(内部)类型的首选设计是什么?,javascript,class-design,Javascript,Class Design,我对构造函数使用Resig的makeClass()方法: // makeClass - By John Resig (MIT Licensed) // Allows either new User() or User() to be employed for construction. function makeClass(){ return function(args){ if ( this instanceof arguments.callee ) { if ( t
// makeClass - By John Resig (MIT Licensed)
// Allows either new User() or User() to be employed for construction.
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, (args && args.callee) ? args : arguments );
} else
return new arguments.callee( arguments );
};
}
// usage:
// ------
// class implementer:
// var MyType = makeClass();
// MyType.prototype.init = function(a,b,c) {/* ... */};
// ------
// class user:
// var instance = new MyType("cats", 17, "September");
// -or-
// var instance = MyType("cats", 17, "September");
//
var MyType = makeClass();
MyType.prototype.init = function(a,b,c) {
say("MyType init: hello");
};
MyType.prototype.Method1 = function() {
say("MyType.Method1: hello");
};
MyType.prototype.Subtype1 = makeClass();
MyType.prototype.Subtype1.prototype.init = function(name) {
say("MyType.Subtype1.init: (" + name + ")");
}
在该代码中,MyType()是顶级类型,MyType.Subfit1是嵌套类型
要使用它,我可以:
var x = new MyType();
x.Method1();
var y = new x.Subtype1("y");
我可以在子类型1()的init()中获取对父类型实例的引用吗?
怎么做 不,除非您编写一个显式跟踪这个“外部”类的类实现,否则Javascript将无法将其提供给您 例如:
function Class(def) {
var rv = function(args) {
for(var key in def) {
if(typeof def[key] == "function" && typeof def[key].__isClassDefinition == "boolean")
def[key].prototype.outer = this;
this[key] = def[key];
}
if(typeof this.init == "function")
this.init.apply( this, (args && args.callee) ? args : arguments );
};
rv.prototype.outer = null;
rv.__isClassDefinition = true;
return rv;
}
var MyType = new Class({
init: function(a) {
say("MyType init: " + a);
say(this.outer);
},
Method1: function() {
say("MyType.Method1");
},
Subtype1: new Class({
init: function(b) {
say("Subtype1: " + b);
},
Method1: function() {
say("Subtype1.Method1");
this.outer.Method1();
}
})
});
var m = new MyType("test");
m.Method1();
var sub = new m.Subtype1("cheese");
sub.Method1();
请注意,有一百万种不同的方式来编写类实现,这只是一个简单的1分钟示例