PDA

View Full Version : [Javascript.new] just for fun: HOW TO MAKE RUBY STYLE DOT NEW


axgle
06-25-2009, 12:37 AM
Object.prototype.new=function(){
return this.apply(this,arguments);
}
var a = Array.new(1,2,3);
var b = Function.new("a,b","return a+b")(1,2);
var c = new Ext.Window({title:'js new', html:'ok',height:100,width:200}).show();
//var d = Ext.Window.new({title:'ruby new?',html:'how to?',height:100,width:200}).show();

console.info(a);
console.info(b);
how to make every object like "new Object(args1,args2,...)" to "Object.new(args1,args2,...)"?:">

mystix
06-25-2009, 01:43 AM
no idea what the whole point of this is, but try

Object.prototype.new = function() {
var me = new this();
return me.constructor.apply(me, arguments);
};

note: works only for Array and Function (and other primitives i guess).

Array.new(1, 2, 3, 4, 5); // returns [1, 2, 3, 4, 5]

Function.new("a,b","return a+b")(1,2); // returns 3




while this works for Ext.Window.

Object.prototype.new = function() {
var me = new this();
me.constructor.apply(me, arguments);

return me;
};


test:

Ext.form.DateField.new({
renderTo: document.body
}); // renders a DateField to document.body

Ext.Window.new({
title: 'ruby new?',
html: 'how to?',
height: 100,
width: 200
}).show();


p.s. what the heck does "just for funny" mean? ah ok. just for laughs.

evant
06-25-2009, 02:02 AM
I think the OP means just for fun.

mystix
06-25-2009, 02:07 AM
oh well. that made for a nice 15 minute post-lunch exercise.

mystix
06-25-2009, 02:22 AM
i give up. i must be doing something wrong somewhere.

axgle
06-25-2009, 05:28 AM
OK,maybe It can workB)
Object.prototype['new']=function(){
var params=[];
var argc=arguments.length;
for(var i=0;i<argc;i++){
params.push('arguments['+i+']');
}
var code='return new this('+params.join(',')+');';
return new Function(code).apply(this,arguments);
}
Ext.Window.new({
title: 'ruby new?',
html: 'how to?',
height: 100,
width: 200
}).show();