在写javascript代码的过程中,我们经常忘记要先new出一个实例,在这种情况下,访问这个实例就会出现异常。
var foo = User(...); // forgot to use the "new" operator
如果想防止这样的情况发生,可以用如下的方法创建类。这也不失为一个好的方法。
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, args );
} else
return new arguments.callee( arguments );
};
}
var User = makeClass();
User.prototype.init = function(first, last){
this.name = first + " " + last;
};
var user = User("John", "Resig");
user.name
// => "John Resig"
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, args );
} else
return new arguments.callee( arguments );
};
}
var User = makeClass();
User.prototype.init = function(first, last){
this.name = first + " " + last;
};
var user = User("John", "Resig");
user.name
// => "John Resig"
