473,770 Members | 1,973 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using eval() for function definition

Hello,

I have this particular problem with eval() when using Microsoft
Internet Explorer, when trying to define an event handler. This is the
code:

function BigObject()
{
this.items = new Array();
this.values = new Array();

this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}

this.makeHandle rs()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
}
}

However, this last code (makeHandlers() method) doesn't work since the
expression "this.value s[i]" automatically belongs to this new
anonymous function, and therefore isn't valid (since the new anonymous
function(s) don't have the "values" attribute. So I tried the
following:
this.items[i].onclick = eval( "function() { alert( " +
this.values[i] + "); }" );
and it worked! ... in Firefox only :( Internet explorer returns
"undefined" for eval( "function() { /* whatever */ ); } " ), for the
same things Firefox perfectly understands, and if I try to make it a
handler, an exception is fired in IE. What do I do? Did I come to the
right conclusion with IE or am I making a banal mistake? Do I need to
find another way of solving this or is there a fix to this solution?

Thank you,
Darko

Feb 19 '07 #1
7 5064
On Feb 19, 4:56 pm, "Darko" <darko.maksimo. ..@gmail.comwro te:
Hello,

I have this particular problem with eval() when using Microsoft
Internet Explorer, when trying to define an event handler. This is the
code:

function BigObject()
{
this.items = new Array();
this.values = new Array();

this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}

this.makeHandle rs()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
}

}

However, this last code (makeHandlers() method) doesn't work since the
expression "this.value s[i]" automatically belongs to this new
anonymous function, and therefore isn't valid (since the new anonymous
function(s) don't have the "values" attribute. So I tried the
following:
this.items[i].onclick = eval( "function() { alert( " +
this.values[i] + "); }" );
and it worked! ... in Firefox only :( Internet explorer returns
"undefined" for eval( "function() { /* whatever */ ); } " ), for the
same things Firefox perfectly understands, and if I try to make it a
handler, an exception is fired in IE. What do I do? Did I come to the
right conclusion with IE or am I making a banal mistake? Do I need to
find another way of solving this or is there a fix to this solution?

Thank you,
Darko
I'm sorry, I had a syntax error in the post I submitted, just in case
someone thinks that is the reason for my troubles, it isn't - it was a
typo just in the post here:
this.makeHandle rs()
{ ...
should have been written:
this.makeHandle rs = function()
{ ...

Feb 19 '07 #2
On Feb 19, 10:56 am, "Darko" <darko.maksimo. ..@gmail.comwro te:
Hello,

I have this particular problem with eval() when using Microsoft
Internet Explorer, when trying to define an event handler. This is the
code:

function BigObject()
{
this.items = new Array();
this.values = new Array();

this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}

this.makeHandle rs()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
}

}
Same thing happens in Lisp:
CL-USER: (let ((foo #1A(1 2 3)))
(funcall (car (loop for i below 3 collect (lambda() (aref
foo i))))))

Error: The subscript 3 exceeds the limit 2 for the first dimension
of the array #(1 2 3).
1 (abort) Return to level 0.
2 Return to top loop level 0.

You're not creating the closure you think you are,
it is binding on i. What you are getting is

function(){aler t(this.values[length]);}

for all of them because i=length at the end of
the loop.

Try this, create a function

function foo(x){return function(){aler t(x)}}

and use

this.items[i].onclick=foo(th is.values[i]);
---
Geoff

Feb 19 '07 #3
On Feb 19, 8:18 pm, "Geoffrey Summerhayes" <sumr...@hotmai l.com>
wrote:
On Feb 19, 10:56 am, "Darko" <darko.maksimo. ..@gmail.comwro te:
Hello,
I have this particular problem with eval() when using Microsoft
Internet Explorer, when trying to define an event handler. This is the
code:
function BigObject()
{
this.items = new Array();
this.values = new Array();
this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}
this.makeHandle rs()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
}
}

Same thing happens in Lisp:
CL-USER: (let ((foo #1A(1 2 3)))
(funcall (car (loop for i below 3 collect (lambda() (aref
foo i))))))

Error: The subscript 3 exceeds the limit 2 for the first dimension
of the array #(1 2 3).
1 (abort) Return to level 0.
2 Return to top loop level 0.

You're not creating the closure you think you are,
it is binding on i. What you are getting is

function(){aler t(this.values[length]);}

for all of them because i=length at the end of
the loop.

Try this, create a function

function foo(x){return function(){aler t(x)}}

and use

this.items[i].onclick=foo(th is.values[i]);

---
Geoff
It actually worked! Thank you a lot! I thought about a similar way,
creating a function object that would receive arguments, and generated
a function, but the way I did it couldn't help neither. This is
perfect, thank you!

Darko

Feb 19 '07 #4
On Feb 19, 8:14 am, "Darko" <darko.maksimo. ..@gmail.comwro te:
On Feb 19, 4:56 pm, "Darko" <darko.maksimo. ..@gmail.comwro te:
Hello,
I have this particular problem with eval() when using Microsoft
Internet Explorer, when trying to define an event handler. This is the
code:
function BigObject()
{
this.items = new Array();
this.values = new Array();
this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}
this.makeHandle rs()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
}
}
However, this last code (makeHandlers() method) doesn't work since the
expression "this.value s[i]" automatically belongs to this new
anonymous function, and therefore isn't valid (since the new anonymous
function(s) don't have the "values" attribute. So I tried the
following:
this.items[i].onclick = eval( "function() { alert( " +
this.values[i] + "); }" );
and it worked! ... in Firefox only :( Internet explorer returns
"undefined" for eval( "function() { /* whatever */ ); } " ), for the
same things Firefox perfectly understands, and if I try to make it a
handler, an exception is fired in IE. What do I do? Did I come to the
right conclusion with IE or am I making a banal mistake? Do I need to
find another way of solving this or is there a fix to this solution?
Thank you,
Darko

I'm sorry, I had a syntax error in the post I submitted, just in case
someone thinks that is the reason for my troubles, it isn't - it was a
typo just in the post here:
this.makeHandle rs()
{ ...
should have been written:
this.makeHandle rs = function()
{ ...
First off: using "eval" in this context is completely inappropriate.
For one thing, you have the "Function" constructor which works in much
the same way; for another, a proper understanding of closures will
help to avoid this problem.

You have inadvertently touched on one of the more advanced topics in
javascript: closures and "this" keyword resolution. Understanding
this is key to using mature JavaScript technique. Please read this
article:

http://www.jibbering.com/faq/faq_notes/closures.html (by this list's
own Richard Cornford)

and then come back if you still have questions.

-David

Feb 19 '07 #5
Darko wrote:
I have this particular problem with eval() when using
Microsoft Internet Explorer, when trying to define an
event handler. This is the code:

function BigObject()
{
this.items = new Array();
this.values = new Array();

this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}
This - addItem - method does not take advantage of its status as an inner
function (its unique identify and the closure resulting form its
assignment). Under those circumstances it would be better to assign it to
the - BigObject.proto ype - so a single function object may be shared as
an instance method of all - BigObject - instances.
this.makeHandle rs()
Noting the correction; this.makeHandle rs = function()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };
In javascript the value of the - this - keyword is determined by how a
function is called. It is not a property of the function objects
themselves. In response to events, a browser calls the functions assigned
to its intrinsic event properties as methods of the DOM Element to which
the handler is assigned, this leaves the - this - keyword referring to
the DOM Element.
}
This method makes no use of its status as an inner function and so should
again be assigned to the prototype.
}

However, this last code (makeHandlers() method) doesn't work
since the expression "this.value s[i]" automatically belongs
to this new anonymous function,
No, it doesn't work because - this - refers to the DOM Element and the -
i - value belongs to the one containing execution and has the value it
had when the - for - loop finished.
and therefore isn't valid (since the new anonymous
function(s) don't have the "values" attribute.
They don't, but it is the DOM Element not having a - values - property
that is significant here.
So I tried the following:
this.items[i].onclick = eval( "function() { alert( " +
this.values[i] + "); }" );
and it worked!
It would be more accurate to say that where it 'worked' it actually
failed to fail as expected. The - eval - function executes its string
argument as a complete javascript Program, and the units that a Program
can be made up of are Statements and FunctionDeclara tions. A
FunctionDeclara tion must have an Identifier as the function name, so your
string is not a syntactically correct FunctionDeclara tion. A statement
may not start with the - function - keyword, so your string is not a
syntactically correct Statement, and so it also cannot be a syntactically
correct javascript Program.

A combination of using - eval - (which often acts to mask errors, or make
them indirect/obscure) , syntax extensions and error tolerance
(particularly in IE's case) may conspire to give the impression of
something that 'works', but there is nothing in the language to suggest
that this would ever be effective code to be writing.
... in Firefox only :( Internet explorer returns
"undefined" for eval( "function() { /* whatever */ ); } " ),
for the same things Firefox perfectly understands, and if I
try to make it a handler, an exception is fired in IE.
You are not allowed to assign the undefined value to an intrinsic event
property in IE.
What do I do?
<snip>

First, learning javascript's syntax might be of some use while attempting
to write it.

You need to have a function that is called as a method of a DOM element
reference a property of a particular javascript object instance, and
employ an individual and unique index with that property. The following
will do that, but you will have to look at the URL reference to
understand why:-

function BigObject(){
this.items = new Array();
this.values = new Array();
}
BigObject.proto type.addItem = function(item){
this.items[this.items.leng th] = item;
};
BigObject.proto type.makeHandle rs = function(){
var i, length = this.items.leng th;
var self = this; // Make the object instance available on the scope
// chain as a - self - variable.
for ( i = 0; i < length; i++ ){
this.items[i].onclick = (function(index ){
return (function(){
alert( self.values[index] ); // self - is resolved
// against the scope
// chain, and resolves as
// a reference to the
// individual javascript
// object instance
// assigned in the
// outermost function with
// the - this - keyword.
});
})(i); // Pass the individual index - i - as an argument to the
// function call that returns the event handling
// function. This allows the event handling function to
// reference its index as the outer unction's - index -
// formal parameter.
}
};
See:-
<URL: http://jibbering.com/faq/faq_notes/closures.html >

Richard.

Feb 19 '07 #6
On Feb 19, 10:31 pm, "Richard Cornford" <Rich...@litote s.demon.co.uk>
wrote:
Darko wrote:
I have this particular problem with eval() when using
Microsoft Internet Explorer, when trying to define an
event handler. This is the code:
function BigObject()
{
this.items = new Array();
this.values = new Array();
this.addItem = function( item )
{
this.items[this.items.leng th] = item;
}

This - addItem - method does not take advantage of its status as an inner
function (its unique identify and the closure resulting form its
assignment). Under those circumstances it would be better to assign it to
the - BigObject.proto ype - so a single function object may be shared as
an instance method of all - BigObject - instances.
The other day I saw in some script the prototype thing, I didn't
really understand what it was for, now I understand a little better,
and the links you gave to me seem to contain more about the issue;
I'll have to give it a closer look. Anyway, sounds like a good idea to
share the function definition among all the function-objects.
>
this.makeHandle rs()

Noting the correction; this.makeHandle rs = function()
{
var i, length = this.items.leng th;
for ( i = 0; i < length; i++ )
this.items[i].onclick = function()
{ alert( this.values[i] ); };

In javascript the value of the - this - keyword is determined by how a
function is called. It is not a property of the function objects
themselves. In response to events, a browser calls the functions assigned
to its intrinsic event properties as methods of the DOM Element to which
the handler is assigned, this leaves the - this - keyword referring to
the DOM Element.
How stupid of me. Of course it's the element the event is about that
the "this" attribute is of, I have already been using it, just didn't
recognise the relation, I completely lost it.
This method makes no use of its status as an inner function and so should
again be assigned to the prototype.
}
So I tried the following:
this.items[i].onclick = eval( "function() { alert( " +
this.values[i] + "); }" );
and it worked!

It would be more accurate to say that where it 'worked' it actually
failed to fail as expected. The - eval - function executes its string
argument as a complete javascript Program, and the units that a Program
can be made up of are Statements and FunctionDeclara tions. A
FunctionDeclara tion must have an Identifier as the function name, so your
string is not a syntactically correct FunctionDeclara tion. A statement
may not start with the - function - keyword, so your string is not a
syntactically correct Statement, and so it also cannot be a syntactically
correct javascript Program.
I don't quite understand what you mean when you say a statement may
not start with the function keyword? How is that? How about function
definitions?
First, learning javascript's syntax might be of some use while attempting
to write it.
Yes, well, I have learnt the 'var' and 'if' keywords, and something
about semicolons, I thought that might do it? ;-)
function BigObject(){
this.items = new Array();
this.values = new Array();}

BigObject.proto type.addItem = function(item){
this.items[this.items.leng th] = item;};

BigObject.proto type.makeHandle rs = function(){
var i, length = this.items.leng th;
var self = this; // Make the object instance available on the scope
// chain as a - self - variable.
for ( i = 0; i < length; i++ ){
this.items[i].onclick = (function(index ){
return (function(){
alert( self.values[index] ); // self - is resolved
// against the scope
// chain, and resolves as
// a reference to the
// individual javascript
// object instance
// assigned in the
// outermost function with
// the - this - keyword.
});
})(i); // Pass the individual index - i - as an argument to the
// function call that returns the event handling
// function. This allows the event handling function to
// reference its index as the outer unction's - index -
// formal parameter.
}
};
Why, thank you a lot! This code was easily conceivable, with the
comments of course, and I took a look in that text, it's bookmarked
all right :) Thanks to you once again!

Feb 20 '07 #7
On Feb 20, 2:23 pm, Darko wrote:
On Feb 19, 10:31 pm, Richard Cornford wrote:
>Darko wrote:
<snip>
>>and it worked!
>It would be more accurate to say that where it 'worked' it actually
failed to fail as expected. The - eval - function executes its string
argument as a complete javascript Program, and the units that a
Program can be made up of are Statements and FunctionDeclara tions.
A FunctionDeclara tion must have an Identifier as the function name,
so your string is not a syntactically correct FunctionDeclara tion. A
statement may not start with the - function - keyword, so your string
is not a syntactically correct Statement, and so it also cannot be a
syntacticall y correct javascript Program.

I don't quite understand what you mean when you say a statement may
not start with the function keyword? How is that? How about function
definitions?
<snip>

The units of a javascript program are FunctionDeclara tions and
Statements. What you are calling a function definition would be the
structure that qualifies as a Function Declaration, and so _not_ a
Statement. The only form of statement that could commence with the -
function - keyword is an ExpressionState ment, and the syntax rules for
the ExpressionState ment explicitly forbid it from commencing with an
opening brace ("{") or the - function - keyword. This is probably to
avoid the result being ambiguous (making it clear that an
ExpressionState ment is not either a Function Declaration or an object
literal).

Richard.

Feb 20 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1912
by: robcarlton | last post by:
hi everybody I've written this function to make a list of all of an objects attributes and methods (not for any reason, I'm just learning) def list_members(obj) l = dir(obj) return map(lambda x : eval('obj.'+x), l) but I get an error saying that obj isn't defined. As I understand it eval has access to the current local namespace, which does contain
10
2403
by: Julian Smith | last post by:
I've been playing with a function that creates an anonymous function by compiling a string parameter, and it seems to work pretty well: def fn( text): exec 'def foo' + text.strip() return foo This can be used like: def foo( x):
12
3458
by: knocte | last post by:
Hello. I have always thought that the eval() function was very flexible and useful. If I use it, I can define functions at runtime!! However, I have found a case where eval() does not work properly. It works, for example, when invoking functions (alert('hello')), but not for defining functions. The case occurs when retrieving the javascript code with
4
3508
by: tozeina | last post by:
Can any one help in this please. I'm using eval function in JavaScript, But when the eval method return a big big number the result will be a number with "E" for example : Eval(1000000000000000000000) will result 1e+21 I need to get the number as it is . can i ?? Thanks in advance
2
3401
by: bylabylamo | last post by:
i have a problem converting a json string that i get from a servlet into a json object using eval function of java script. any one please help me..........
6
3633
by: vasudevram | last post by:
Hi group, Question: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? I wrote a function to generate other functions using something like eval("def foo: ....") but it gave a syntax error ("Invalid syntax") with caret pointing to the 'd' of the def keyword.
3
1657
by: HareshKarkar | last post by:
Hi , I'm calling some Javascript function to write value in the layer. I'm trying to achieve it by using eval() function. Please look at the code below: function showMore(tempLayerNum, tempLayerName) { var temp = "step"+tempLayerNum+"More".toString(); eval(temp).write("Hi"); }
6
5931
by: RandomElle | last post by:
Hi there I'm hoping someone can help me out with the use of the Eval function. I am using Access2003 under WinXP Pro. I can successfully use the Eval function and get it to call any function with or without parms. I know that any function that is passed to Eval() must be declared Public. It can be a Sub or Function, as long as it's Public. I even have it where the "function" evaluated by Eval can be in a form (class) module or in a standard...
2
20661
by: rdemarco | last post by:
Hi guys I'm trying to use the eval() function to run code that I have previously compiled via string concatenation. Some of it works, for example, I can set the focus to a combo box called 'AssetIDLookup', which is on the other form, with this code: 'First building the string using variables: buildCommandString = "Forms!" & AppropriateFormName & "!AssetIDLookup.setfocus" 'Now use eval() and pass the string to have it converted to a...
0
10254
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8929
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7451
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.