1
我使用的构造Resig的makeClass()的方法:Javascript:嵌套(内部)类型的首选设计是什么?
// 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.Subtype1是嵌套类型。
要使用它,我可以这样做:
var x = new MyType();
x.Method1();
var y = new x.Subtype1("y");
我能到父类型的实例的引用,在init()为Subtype1内()? 如何?
注意,有一百万个不同的方式来写一个类实现,这只是一个简单的1分钟例如 – Tyson 2009-12-17 22:59:10
谢谢你,这完美地工作。 – Cheeso 2009-12-18 03:50:06