【发布时间】:2009-11-27 20:37:21
【问题描述】:
在OO Javascript constructor pattern: neo-classical vs prototypal 中,我了解到使用原型继承的构造函数可以比使用所谓的neo-classical 模式和闭包的构造函数快10 倍(或更多),正如Crockford 在他的“Good Parts”一书和演示文稿中提出的那样。
出于这个原因,一般来说,更喜欢原型继承似乎是正确的事情。
问题有没有办法将原型继承与模块模式结合起来,以便在必要时允许私有变量?
我的想法是:
// makeClass method - By John Resig (MIT Licensed)
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, args.callee ? args : arguments );
} else
return new arguments.callee( arguments );
};
}
// =======================================================
var User = makeClass();
// convention; define an init method and attach to the prototype
User.prototype.init = function(first, last){
this.name = first + " " + last;
};
User.prototype.doWork = function (a,b,c) {/* ... */ };
User.prototype.method2= (function (a,b,c) {
// this code is run once per class
return function(a,b,c) {
// this code gets run with each call into the method
var _v2 = 0;
function inc() {
_v2++;
}
var dummy = function(a,b,c) {
/* ... */
inc();
WScript.echo("doOtherWork(" + this.name + ") v2= " + _v2);
return _v2;
};
var x = dummy(a,b,c);
this.method2 = dummy; // replace self
return x;
};
})();
这不太对。但它说明了这一点。
有没有办法做到这一点,值得吗?
【问题讨论】:
标签: javascript oop class-design