473,794 Members | 2,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new Function(...) abuse in FAQ?

Hi,

Why does http://www.jibbering.com/faq/ uses new Function constructor
instead of function expressions (function(...) { ... }) when defining
new functions? E.g. for LTrim and toFixed. Is the reason that you want
to avoid accidental closures? Or does some obscure browser does not
support function expressions?

This just looks weird, given that http://www.jibbering.com/faq/#FAQ4_40
says to only use eval() (which is not really much different from new
Function()) only for evaluating code that only becomes known at
run-time.

Nickolay

Jan 22 '07 #1
14 1560
Nickolay Ponomarev wrote:
Hi,

Why does http://www.jibbering.com/faq/ uses new Function constructor
instead of function expressions (function(...) { ... }) when defining
new functions?
I thought the same

<URL:
http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/f40e66f39de1fd2 7/d3f306c325bb00a f?lnk=gst&q=pet ermichaux+faq+f unction+constru ctor&rnum=1#d3f 306c325bb00af>
Peter

Jan 22 '07 #2

Peter Michaux wrote:
Nickolay Ponomarev wrote:
Hi,

Why does http://www.jibbering.com/faq/ uses new Function constructor
instead of function expressions (function(...) { ... }) when defining
new functions?

I thought the same

<URL:
http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/f40e66f39de1fd2 7/d3f306c325bb00a f?lnk=gst&q=pet ermichaux+faq+f unction+constru ctor&rnum=1#d3f 306c325bb00af>

Nice, but I don't see an explanation why it has to be the way it is
currently in that thread.

As to what's wrong with new Function(),
a) it gives a bad example
b) the code is supplied as a string, which leads to
b-1) syntax highlighters not working on it =harder to read, easier
to miss an error
b-2) the need for extra escapes (took me several seconds to see that
\\s in regexp in the trim implementation was not an error.

Nickolay

Jan 22 '07 #3

Nickolay Ponomarev wrote:
Peter Michaux wrote:
Nickolay Ponomarev wrote:
Hi,
>
Why does http://www.jibbering.com/faq/ uses new Function constructor
instead of function expressions (function(...) { ... }) when defining
new functions?
I thought the same

<URL:
http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/f40e66f39de1fd2 7/d3f306c325bb00a f?lnk=gst&q=pet ermichaux+faq+f unction+constru ctor&rnum=1#d3f 306c325bb00af>
Nice, but I don't see an explanation why it has to be the way it is
currently in that thread.

As to what's wrong with new Function(),
a) it gives a bad example
b) the code is supplied as a string, which leads to
b-1) syntax highlighters not working on it =harder to read, easier
to miss an error
b-2) the need for extra escapes (took me several seconds to see that
\\s in regexp in the trim implementation was not an error.
c) it is inefficient (performance-wise) for the same reason that "eval"
is inefficient - the code is re-parsed each time it's used, instead of
only once, as normal functions are
d) it discourages beginning JS programmers from learning about properly
dealing with closures and memory leak issues
e) it doesn't have the advantage of lexical scoping, which is an
important feature in JavaScript functions (when properly used)
f) it encourages bad program design and inefficient code, as decisions
that should be made before writing can be put off until run-time (as
string concatenations, for example)

See also:

http://developer.mozilla.org/en/docs...on#Description
http://msdn2.microsoft.com/en-us/library/ckas3s0w.aspx
http://javascript.crockford.com/code.html (scroll to bottom)
http://javascript.crockford.com/survey.html (scroll to "Function
constructor" section)

Let the thing die, finally.

-DG

Jan 22 '07 #4
Nickolay Ponomarev wrote:
Hi,

Why does http://www.jibbering.com/faq/ uses new Function
constructor instead of function expressions (function(...) { ... })
when defining new functions?
Mostly because much of it was written half a decade ago when anything else
would not have been cross-browser. It has remained because it a. it still
works fine, b. no compelling argument has ever been presented for changing
it (leaving it largely a matter of taste as to whether it gets changed).
E.g. for LTrim and toFixed. Is the reason that
you want to avoid accidental closures?
Avoiding needlessly forming closures is a reason for using the function
constructor to create functions, though those specific examples would form
problematic closures.
Or does some obscure browser does not
support function expressions?
What a strange question. No pre-ECMA 262 3rd edition implementations can be
expected to support inner functions, and some certainly did not.
Fortunately, with the standard having remained stable for so long we have
just arrived (over the last two or three years) at the point where current
browsers are all, more or less, bug free ECMA 262 3rd edition
implementations . Probably, Konqueror 2 was the most recent browser that did
not understand nested functions. Konqueror 3.x is currently pretty close to
being ECMA 262 3rd Ed.
This just looks weird, given that
http://www.jibbering.com/faq/#FAQ4_40 says to only use eval()
(which is not really much different from new Function()) only
for evaluating code that only becomes known at run-time.
While all (at least almost all) of the abuses of - eval - can be reproduced
using the Function constructor is does not then follow that uses of the
function constructor are then all equivalent to - eval - abuses. Indeed, it
is difficult to see how the use of the - Function - constructor to construct
function objects could qualify as an abuse of it.

Richard.
Jan 22 '07 #5
Nickolay Ponomarev wrote:
<snip>
Nice, but I don't see an explanation why it has to be the
way it is currently in that thread.

As to what's wrong with new Function(),
a) it gives a bad example
You should not expect anyone to give much credence to an argument that says
"it gives a bad example" is you do not state what it is that it gives an
example of, or what it is that is bad about it.

Remember that the world of web development is plagued with uninformed
opinions, hearsay, lies, poor advice, rumours and mystical incantations. We
even have browser's like Mozilla/Gecko spitting out spurious and bogus
"warnings" (along side very reasonable warnings, but to the detriment of
their general credibility) if you are fool enough to turn that facility on.

If there is a reason for a particular course of action that reason can be
stated in full and so judged on its own merits. In this very thread that is
already at least one statement that is factually false, but still being put
forward as a reason for a particular course of action. We would not want to
take your "it gives a bad example" seriously and then discover that it was
motivated by a similar misconception.
b) the code is supplied as a string, which leads to
b-1) syntax highlighters not working on it =harder to
read, easier to miss an error
True, but that only leads to the position that creating complex functions
with the Function constructor is probably not a good idea. Where a function
body consists of only a single statement it is unlikely that either of
syntax highlighting or error locating are going to be significant issues. A
reasonable cut-off might be proposed at, say, 4 statements.
b-2) the need for extra escapes (took me several seconds
to see that \\s in regexp in the trim implementation was not
an error.
But for most functions constructed in that way no escaping is necessary at
all. And with regular expressions you have similar escaping issues when
using the RegExp constructor to process a string into a regular expression
object (would that imply never using that constructor?).

Generally I am not in favour of people even attempting to script the
creation of scripts (which is what constructing function bodies as strings
and then turning those into function objects with the Function constructor
is), but I am also not in favour on knee-jerk reactions to particular (and
potentially, even if rarely) useful constructs. An ability to make informed
decisions about what is done is far more useful.

Richard.
Jan 22 '07 #6
David Golightly wrote:
Nickolay Ponomarev wrote:
>Peter Michaux wrote:
Nickolay Ponomarev wrote:
Hi,

Why does http://www.jibbering.com/faq/ uses new Function
constructor instead of function expressions (function(...) { ...
}) when defining new functions?

I thought the same

<URL:
http://groups.google.com/group/comp..../thread/f40e66
f39de1fd27/d3f306c325bb00a f?lnk=gst&q=pet ermichaux+faq+f unction+constru ctor&
rnum=1#d3f306c3 25bb00af>
>
Nice, but I don't see an explanation why it has to be the way it is
currently in that thread.

As to what's wrong with new Function(),
a) it gives a bad example
b) the code is supplied as a string, which leads to
b-1) syntax highlighters not working on it =harder to read, easier
to miss an error
b-2) the need for extra escapes (took me several seconds to see that
\\s in regexp in the trim implementation was not an error.

c) it is inefficient (performance-wise) for the same reason
that "eval" is inefficient - the code is re-parsed each time
it's used, instead of only once, as normal functions are
Not true. Once a function object has been constructed the method of
construction no longer has any influence on its performance. And while
generating a function object from a string at runtime can be slow in some
environments such a method of function object creation has been demonstrated
to be (at least some of the time) the fasted available in others (IE 6).
d) it discourages beginning JS programmers from learning
about properly dealing with closures and memory leak issues
Beginner javascript programmers are not going to easily understand closures
whatever you do. However, if they create faction objects with the
constructor they will not be creating closures so they will not need to
clean them up. Though it could easily be argued that there can be no such
thing as "properly dealing with closures and memory leak issues" because if
things were being done "properly" (by the browser makers) there would be no
memory leak issues.
e) it doesn't have the advantage of lexical scoping,
which is an important feature in JavaScript functions
(when properly used)
Lexical scoping is not "an advantage", it is a reality. Its existence in the
language introduces the possibility to apply designed control over the scope
chains of functions, but there is only one way of creating a function with
the shortest possible scope chain from within another function, and that is
by using the Function constructor. Full control over the scope chains of
functions requires an ability to fully control the scope chains of function
objects, including the ability to create a function with the minimum scope
chain.
f) it encourages bad program design
It facilitates designed control over an important aspect of function
objects.
and inefficient code,
Is that assertion a result of you false belief that the functions is
re-parsed each time it is executed?
as decisions that should be made before writing can be put off
until run-time (as string concatenations, for example)
<snip>

A decision that can be made at the design stage should not be put off until
run-time, but not all decisions can be made at that point.

Jan 22 '07 #7
On Jan 23, 12:59 am, "Richard Cornford" <Rich...@litote s.demon.co.uk>
wrote:
Nickolay Ponomarev wrote:<snip>
As to what's wrong with new Function(),
a) it gives a bad example
You should not expect anyone to give much credence to an argument that says
"it gives a bad example" is you do not state what it is that it gives an
example of, or what it is that is bad about it.
I said what's bad about it right below. The reason I started with (a)
is that this is what I'm mainly concerned about. I would expect clj FAQ
to give good examples.
We even have browser's like Mozilla/Gecko spitting out spurious and bogus
"warnings"
Any examples? (I know this is off-topic, but since I'm a bit familiar
with moz and never heard of these, you got me interested)
Why does http://www.jibbering.com/faq/ uses new Function
constructor instead of function expressions (function(...) { ... })
when defining new functions?
Mostly because much of it was written half a decade ago when anything else
would not have been cross-browser. It has remained because it a. it still
works fine, b. no compelling argument has ever been presented for changing
it (leaving it largely a matter of taste as to whether it gets changed).
You could save me and yourself some time by only posting this. You
answered my question. Thanks

Nickolay

Jan 23 '07 #8
Nickolay Ponomarev wrote:
On Jan 23, 12:59 am, Richard Cornford wrote:
>Nickolay Ponomarev wrote:<snip>
>>As to what's wrong with new Function(),
a) it gives a bad example
You should not expect anyone to give much credence to an argument that says
"it gives a bad example" is you do not state what it is that it gives an
example of, or what it is that is bad about it.
I said what's bad about it right below.
So that was that strings are not internally syntax highlighted and that
it might be difficult to spot code errors in such strings. Both of
which are largely mitigated if the contents of function body strings
used with the Function constructor are limited in their internal
complexity. Certainly not enough to justify labelling their use as
giving "a bad example".
The reason I started with (a)
"it gives a bad example" is hardly a reason, as it does not state what
that bad example is, or what it bad about it.
is that this is what I'm mainly concerned
about. I would expect clj FAQ to give good examples.
It is not necessarily possible to regard any simple example as good or
bad. You have concerned yourself with the explicit declaration of
variables (in a nearby thread), but what is to stop someone seeing an
example of such and making a bad application of a declaration such as
features in the second example of code in what follows?
>We even have browser's like Mozilla/Gecko spitting out spurious and bogus
"warnings"

Any examples? (I know this is off-topic, but since I'm a bit familiar
with moz and never heard of these, you got me interested)
Given the code:-

if(window.clipb oardData){
alert('clipboar d')
}

Mozilla 1.6 (for no other reason than it is the Mozilla version on this
machine) outputs the warning:-

"Warning: reference to undefined property window.clipboar dData"

- while with:-

if((typeof window.clipboar dData) == 'object'){
alert('maybe clipboard, or null')
}

- it does not. In the case of the first code the property accessor -
window.clipboar dData - is evaluated into a Reference type, a value
retrieved using that Reference type and that value type-converted to
boolean. In the second case the property accessor -
window.clipboar dData - is evaluated into a Reference type, a value
retrieved using that Reference type and then the type of the value used
to determine one of a set of string values, which is then compared with
a string literal to produce a boolean result.

If any point in those processes can be ladled as a "reference to
undefined property" that should occur in the process of using the
Reference type to retrieve a value (as the creation of the Reference
type has no interest in whether any object assigned to its 'base'
property has a property with the name used as its 'propertyName'
property). Both of the examples above use the same Reference type to
retrieve the same value, so if one produces a warning and the other
does not then either the warning it spurious when it is produced in
the first case or its absence is bogus in the second.

Given the code:-

function testFunc(param) {
var param; // This is a "bad" application of the otherwise "good"
// declaration of local variables.
}

Mozilla outputs the warning:-

"Warning: variable param hides argument"

- and that is an absolute lie. ECMA 262 is very clear about how such
code should be handled (Section 10.1.3) and not only does the - var
param; - not "hide" the - param - formal parameter it is actually
specified as doing nothing (that is, the local variable declaration
does not replace the pre-existing property of the Variable object with
the name - param -, and it does not modify its value). It would be
possible for the warning to express the pointlessness of declaring a
local variable with the same name as a function's formal parameter, but
outputting a factually false statement instead is wrong, and
undermines the credibility of all the warnings generated on the system.
>>Why does http://www.jibbering.com/faq/ uses new Function
constructor instead of function expressions (function(...) { ... })
when defining new functions?

Mostly because much of it was written half a decade ago when anything else
would not have been cross-browser. It has remained because it a. it still
works fine, b. no compelling argument has ever been presented for changing
it (leaving it largely a matter of taste as to whether it gets changed).
Are you re-ordering the material you are quoting (without stating as
much)? That would generally be regarded as disingenuous.
You could save me and yourself some time by only posting this. You
answered my question.
<snip>

I was interested in whether you would present any compelling arguments
for changing the FAQ. You have not.

Richard.

Jan 23 '07 #9
Richard Cornford said the following on 1/23/2007 6:05 AM:
Nickolay Ponomarev wrote:
<snip>
>You could save me and yourself some time by only posting this. You
answered my question.
<snip>

I was interested in whether you would present any compelling arguments
for changing the FAQ. You have not.
<GYou have noticed a lack of change in the code in the FAQ, no? <G>

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 23 '07 #10

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

Similar topics

5
3454
by: Paradox | last post by:
I would like to call a function whose name I supply at runtime. Something like this but it didn't work functionName = 'run' instance = ClassDef() args = #want the dynamic equivalant of #instance.run(*args)
3
14953
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
9
2162
by: Andy Lomax | last post by:
gcc 3.3 allowed a typedef for a function pointer to contain default argument specifications; for example: typedef int (*foo) (int, int, int=0, bar=0); However, it turns out that this is illegal and gcc 3.4 prohibits it. Problem: I've got a lot of code that uses this 'feature', and I can't move the default specifications into the function declaration or definition, because they're not visible. This means that I can no longer call...
12
38512
by: Huskier | last post by:
Hi all: I want to pass a class-member function to pthread_create, and my code is in the following, but I don't know how to pass myobj.thread_function to pthread_create function. #include <pthread.h> class test { public:
5
2171
by: Giannis Papadopoulos | last post by:
I have the following code #include <stdio.h> void a(void) { printf("a called.\n"); } int b(void) { printf("b called.\n");
11
21933
by: Ken Varn | last post by:
I want to be able to determine my current line, file, and function in my C# application. I know that C++ has the __LINE__, __FUNCTION__, and __FILE___ macros for getting this, but I cannot find a C# equivalent. Any ideas? -- ----------------------------------- Ken Varn Senior Software Engineer Diebold Inc. varnk@diebold.com
10
2304
by: Robert Skidmore | last post by:
Take a look at this new JS function I made. It is really simple but very powerful. You can animate any stylesheet numeric value (top left width height have been tested), and works for both % and px values. Works in both ie and firefox. Parameters styleType = top | left | width | height toNumber = the new value of the style then you pass in as many ids as you would like.
9
2745
by: Khookie | last post by:
Hi all, I was wondering what was considered macro abuse. Specifically I implemented a key-value array (or dictionary), as per below. Notice the use of macros - would that be considered alright? #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
9
1595
by: Gilles Ganault | last post by:
Hello As a newbie, it's pretty likely that there's a smarter way to do this, so I'd like to check with the experts: I need to try calling a function 5 times. If successful, move on; If not, print an error message, and exit the program: ===== success = None
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10433
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
10000
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
9035
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
7538
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
5436
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...
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
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.