alert('x='+x)

O

optimistx

How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.

I think there is so simple solution for this that I probable will feel very
embarrassed after getting the answer. So I blush in advance :).
 
E

Evertjan.

optimistx wrote on 05 apr 2004 in comp.lang.javascript:
How to write a function f(x) or f('x') so that it produces the same
output as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the
variable value one would save a lot of typing during one's lifetime.

function toAlert(x){
alert('toAlertParameter = "'+x+'"');
}

toAlert('Try me out')
toAlert( 355/113)
 
O

optimistx

Evertjan. said:
optimistx wrote on 05 apr 2004 in comp.lang.javascript:


function toAlert(x){
alert('toAlertParameter = "'+x+'"');
}

toAlert('Try me out')
toAlert( 355/113)

Thanks Evertjan for trying. I was probably a bit unclear when asking. After
posting I could not resist trying to find a solution anyhow. One way was to
use the 'evil' eval function like this:

alertt=function(){
var s='';
for (var i=0;i<arguments.length;i=i+1){
s+=arguments+'='+eval(arguments)+'\n';
}
alert(s);
}
// example usage:
var x=3;
var y='abc';

alertt('x','y','document.title');
// the output is an alert box with e.g.
x=3
y=abc
document.title=example document title

and
alertt('x') gives an alert box with text
x=3

Sorry to bother readers perhaps in vain. Hopefully the code is useful for
someone else except me :).

By the way, is there a way to avoid eval() above?
 
E

Evertjan.

optimistx wrote on 05 apr 2004 in comp.lang.javascript:
By the way, is there a way to avoid eval() above?

There is always a way to avoid evil [remember sunday school]:

toAlert=function(){
var s='';
for (var i=0;i<arguments.length;i++)
s+=arguments+' = '+window[arguments]+'\n';
alert(s);
}
var x=5
var y=x*x
toAlert('x','y')


this does only work for global variables,
not for 'document.title',
nor for '2*3*4'.
 
R

Richard Cornford

optimistx wrote:
alertt=function(){
var s='';
for (var i=0;i<arguments.length;i=i+1){
s+=arguments+'='+eval(arguments)+'\n';
}
alert(s);
}

Sorry to bother readers perhaps in vain. Hopefully the code is useful
for someone else except me :).

The code is unlikely to be of that much use to you either. You will be
able to display a number of global variable names and values along with
the property accessors and values of property accessors that use
absolute references. But you won't have much joy with local variables,
property accessors relative to the - this - keyword and many similar
conditions. Consider:-

function demonstration(s, p){
var d = document;
for(var c = 0;c < 2;c++){
alertt('c','s','p','d.title','arguments[2]');
}
}

The result would be; 'c' is probably undefined, unless there is also a
global variable called 'c' and that would not be the 'c' that was
interesting in the context of the call, 's' refers to the string that is
being built inside the - alertt - function, 'p' is like 'c' as it is a
parameter to the outer function, 'd.title' will produce an error, unless
there is a global variable 'd' that refers to an object, and
'arguments[2]' will refer to the string 'p' (the third argument to -
alertt). Nothing that might be interesting in the context of the call
to - alertt - is reported.

As an aid to development it would only really be useful in referring to
global variables and, as general programming advice is to create as few
global variables as possible, it will have limited practical
applications. It may even encourage you to adopt an inappropriate
programming style in order to make use of this tool.

Richard.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.

It cannot be done with f(x), as the name is not then passed. But

function f(x) { alert(x+'='+eval(x)) }

will do it.

A general expression can be passed; f("3+5"), f("Math.sqrt(+X)").

Since that will not show the difference between x="" & x=" ", you may
want a different version for strings,

function s(x) { alert(x+'="'+eval(x)+'"') }

There is a way, I suspect, of doing it without eval.
 
E

Evertjan.

Richard Cornford wrote on 05 apr 2004 in comp.lang.javascript:
The code is unlikely to be of that much use to you either.

You are making a mistake here Richard.

Code in this NG is not only useful for execution but also,
and perhaps even more so for discussion and learning.

This code as such is perhaps totally unuseful in use, but I at least
learned that the window[x] form of global variables doesn't work if x is a
formula.

That is I did know it, otherwise it would be equally evil as eval(), but
now I is in my active memory for a while.

To construct a global variable name dynamicly it is very usefull:

var window["varNr"+n*2] = 7*n;
 
R

Richard Cornford

Evertjan. said:
Richard Cornford wrote on 05 apr 2004 in comp.lang.javascript:

You are making a mistake here Richard.

Code in this NG is not only useful for execution but also,
and perhaps even more so for discussion and learning.

Fair enough. I was thinking of the - alertt - function in terms of how
useful it would be for the purpose for which it was designed (alerting
name value pairs of variables, etc). Its limitations may well prove
educational.
This code as such is perhaps totally unuseful in use, but I at least
learned that the window[x] form of global variables doesn't work if x
is a formula.

That is I did know it, otherwise it would be equally evil as eval(),
but now I is in my active memory for a while.

To construct a global variable name dynamicly it is very usefull:

var window["varNr"+n*2] = 7*n;

I would suggest that the global object is not the best repository for
dynamically created properties and their corresponding values.

Richard.
 
O

optimistx

Thanks to Richard Cornford for revealing the limitations of the proposed
code. It saved me a lot of testing time and possible frustration, and the
remarks about good coding style are necessary for me to remember. Evertjan's
attitude makes me feel happy, thanks :).

When talking about inner functions there was an encouraging note from an
expert (was it Crockford? His home pages are a wonderful source of ideas)
that 'almost anything can be done with those'. It were a bit strange that
one could calculate the global variable value when knowing is name (as a
string), but not local. The flexibility of the Javascript language has
surprised me, but are the limits here now?
 
R

rh

Dr said:
It cannot be done with f(x), as the name is not then passed. But

function f(x) { alert(x+'='+eval(x)) }

will do it.

A general expression can be passed; f("3+5"), f("Math.sqrt(+X)").

Since that will not show the difference between x="" & x=" ", you may
want a different version for strings,

function s(x) { alert(x+'="'+eval(x)+'"') }

Or, something in the nature of the following framework:

ALERT = eval; // Slip sheep's clothing on nasty wolf!

function fmt(arg) { // Create eval-ready alert string
var varList = arg.split(",");
for (var k= 0, str = ""; k < varList.length; k++) {
str += "+'\\n"+varList[k]+ ": '"
+"+ (( typeof "+varList[k]+" == 'object') ? Dumper("+varList[k]
+") : "+varList[k]+"+ ' type: '+ typeof "+varList[k]+" )";
}
return "alert(" +str.substr(1)+")";
}

function test(a,b) {
var c = "local variable";
var d= document.title;
var e = { propName : "property value" };
ALERT(fmt("a,b,c,d,e"));
}

test("arg1",2);

which extends the display to include objects.
___________
Notes:

- Creating the ALERT reference to the built-in "eval" function
appears to work in IE 6 and Opera 7.11. It fails in Netscape/Mozilla
in that local execution context is not maintained (however, the above
works if eval is used without substitution).

- Dumper is an object formatting function from the following
reference:

<url:http://groups.google.ca/groups?q="m...g=d&[email protected]&rnum=7>

- It appears that the line

DumperTagProperties["OPTION"] = ['text','value','defaultSelected'];

needs to be included (at least currently) if the object to be
formatted references an element from the DOM (as per the last line of
the example given in the reference). Without it, the library code
loops when executing Dumper(x);.
___________
There is a way, I suspect, of doing it without eval.

I confess to being doubtful. It would seem to me that eval is the only
mechanism available that is going to allow insertion/execution of code
that takes on the required context.

../rh
 
R

Richard Cornford

rh wrote:
ALERT = eval; // Slip sheep's clothing on nasty wolf!
Notes:

- Creating the ALERT reference to the built-in "eval" function
appears to work in IE 6 and Opera 7.11. It fails in Netscape/Mozilla
in that local execution context is not maintained (however, the above
works if eval is used without substitution).
<snip>

Failure should be expected in that context as ECMA 262 3rd ed. Section
15.1.2.1 ends:-

| If value of the eval property is used in any way other than
| a direct call (that is, other than by the explicit use of
| its name as an Identifier which is the MemberExpression in
| a CallExpression), or if the eval property is assigned to,
| an EvalError exception may be thrown.

Richard.
 
F

Fox

sorry for the top post... but the subject has been made thoroughly familiar.

No need for eval...
and, if I understand what you're trying to get at...

// if title is set in html:
<title>test of compoundAlert</title>
// otherwise
document.title = "test of compoundAlert";


<script...

// globals are children of window
// except those specifically attached to document [window.document]

// some stuff to test:

var c = 123;
var str = "this is a string";
var f = function () {
var local = "test";
return local + " this";
}

//I'm gonna go out on a limb here -- just for grins:

function
myObj() {
this.prop = "property";
this.meth = function(arg)
{
return arg;
}
}

var o = new myObj();


// gonna need this to grab the object constructor's name:

function
getConstructor(o)
{
var s = new String(o.constructor);

// grab everything after 'function and before '('
var part = s.match(/function\s+([^\(]+)/);

var name = part ? part[1].replace(/ /g,"") : "function"; // see ** note

// the replace strips any unwanted spaces due to
// "coding style" of: function myObj ( arglist )...
return name;
}

/* ** note: if object is declared:

myObj = function() {...}

"myObj" will not be returned -- "function" will --
and the variable name will be used in compoundAlert


*/


function
compoundAlert()
{

var format = "";

for(var i = 0; i < arguments.length; i++)
{
var argname = arguments;
// test for document element otherwise use window
var parent = argname.indexOf("document.") != -1 ? document : window;

if(parent == document)
argname = argname.replace(/document\./,"");

var type = typeof(parent[argname]); // use associative indexing
var value = parent[argname];

format += "argument name: " + argname + "\n" +
"argument type: " + type + "\n" +
"value of argument:\n" + value + "\n\n";

// just for grins... a little lagniappe... expand objects...
if(type == "object")
{
var tmp = parent[argname];
var cnst = getConstructor(tmp); // const is reserved keyword
if(cnst == "function") // failsafe
cnst = argname;

format += "Object: " + cnst + "\n";

for(var a in tmp)
{
format += a + ": " + tmp[a] + "\n";
}
format += "\n";
}

}

alert(format);
}

compoundAlert('c','str','f','document.title', 'o');

// all must be passed as strings for varname = varvalue formatting


should get you started... Things like "Math" methods, etc... are not
covered here -- an exercise for you to work out (not that there's really
anything useful to get -- Math methods are native code and will display
'[native code]')


if you have any trouble running this, let me know -- i developed it on a
pc and hand-copied it over to a mac, made several revisions and patches
before sending...there might be typos.




Fox
****************
 
R

rh

Richard said:
rh wrote:


<snip>

Failure should be expected in that context as ECMA 262 3rd ed. Section
15.1.2.1 ends:-

| If value of the eval property is used in any way other than
| a direct call (that is, other than by the explicit use of
| its name as an Identifier which is the MemberExpression in
| a CallExpression), or if the eval property is assigned to,
| an EvalError exception may be thrown.

But that doesn't include "may produce invalid or unintended results"
as an alternative. So, as I read it, failure should be anticipated
based on the possibility of an exception being thrown, but not
expected.

Where I would have expected an exception is on an assignment to eval.
Interestingly though :~/, all browsers mentioned above seem to be
quite willing to allow an assignment to eval without producing an
exception.

So basically, it seems your allowed to mess with eval if the browser
doesn't object. And should one decide to do so, Jackass TV is sure to
deny any responsibility for the consequences. :)

../rh
 
N

Nathan Sweet

There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}
 
R

rh

There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}

Just to tickle yourself further, you might try:

function test(){
var a = "asd";
var b = "b";
alertt( b );
alertt( a );
}

Math.random could also used as a way to associate variable names with
incorrect values. It makes debugging a real riot. ;-)

Note that "caller" is deprecated as of JavaScript 1.3, and nonetheless
it has a null value by definition when the call is made from the
global environment ...

../rh
 
C

Cenekemoi

Bonjour à Nathan Sweet said:
There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}

For "global variables" :

foncAlert( s ) {
alert( s +" = "+ window[ s ] );
}

foncAlert( "nom_var" );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top