给定构造函数和参数列表,求构造实例
/** * Note: This function uses window.eval, * which means the function is not available in strict mode */ function newInstance(constrcutor,args){ var length=args.length; var cacheKey="$"+length; var f=newInstance[cacheKey]; if(!f){ var values=new Array(length); for(var i=0;i<length;i++){values[i]="arguments["+i+"]";} f=eval("(function(){return new this("+values.join(",")+");})"); newInstance[cacheKey]=f; } return f.apply(constrcutor,args); } /** * @example */ var values=[2015,4,14,9,17,4,5]; var date=newInstance(Date,values);//same as new Date(2015,4,14,9,17,4,5); /** * @example */ function Point(x,y){ this.x=x; this.y=y; } var x_y=[0,0]; var point=newInstance(Point,x_y);//same as new Point(0,0);
此功能的应用场景不广,但也算填补了JavaScript应用层的一个空白
时间: 2024-10-07 22:48:35