I
Ivo
How do I make the magic 'this' variable refer to an object of my choice, in
a string of code which is to be eval'ed?
Say, I have an object, an array with four elements:
var myobject = [1,2,3,4];
and a string of Javascript:
var mystring = 'alert(this.length)';
When I interpret mystring, I want 'this' to refer to myobject, and get
alerted "4". I have tried:
with( myobject ) { eval( mystring ); }
and
eval( 'with( myobject ) { ' + mystring + ' }' );
but it gives me the length of the window, "0", as if 'this' is not set where
I want it. Variations on the theme have all the same result.
A clumsy solution is to replace the actual occurances in the string:
eval( mystring.replace( /this/g, 'myobject' ) );
That works for simple strings, but I am not sure about more demanding
statements with complex references.
Even more clumsy is using the prototype to add a method:
myobject.constructor.prototype.eva = function( s ) { eval(s); };
myobject.eva( mystring );
Do all kinds of objects and elements have a constructor property which
allows such addition?
Hope I made the issue clear, all ideas appreciated,
Ivo
a string of code which is to be eval'ed?
Say, I have an object, an array with four elements:
var myobject = [1,2,3,4];
and a string of Javascript:
var mystring = 'alert(this.length)';
When I interpret mystring, I want 'this' to refer to myobject, and get
alerted "4". I have tried:
with( myobject ) { eval( mystring ); }
and
eval( 'with( myobject ) { ' + mystring + ' }' );
but it gives me the length of the window, "0", as if 'this' is not set where
I want it. Variations on the theme have all the same result.
A clumsy solution is to replace the actual occurances in the string:
eval( mystring.replace( /this/g, 'myobject' ) );
That works for simple strings, but I am not sure about more demanding
statements with complex references.
Even more clumsy is using the prototype to add a method:
myobject.constructor.prototype.eva = function( s ) { eval(s); };
myobject.eva( mystring );
Do all kinds of objects and elements have a constructor property which
allows such addition?
Hope I made the issue clear, all ideas appreciated,
Ivo