473,856 Members | 1,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JavaScript global object

Hello,

there were times when I used to be looking for a way to access
JavaScript Global object similar to those found in VBScript or PHP
($GLOBALS). At present this has only academic value for me. I was doing
research on JavaScript inheritance recently (simplifying it in
particular) and after reading 10.1.1, 10.1.3 and some other sections of
ECMA262 [1] I got a hint on accessing global object from different than
global scope.

Below is my example (please note that the host is WSH, feel free to
change WScript.Echo to your favourite output call):
myGlobal = this;

function AddVar (id, val)
{
myGlobal[id] = val;
}

function EvalCode (code)
{
myGlobal.eval(c ode);
}

AddVar("roman", 100.1);

WScript.Echo("r oman=" + roman);

EvalCode("funct ion TestEval1 (x,y) { return x+y; }")

// this fails
//WScript.Echo( "TestEval1(150, 100) = ", TestEval1(150,1 00) );

EvalCode("TestE val2 = function (x,y) { return x-y; }")

// this passes
WScript.Echo( "TestEval2(150, 100) = ", TestEval2(150,1 00) );

function EnumProp (o)
{
for(var k in o)
WScript.Echo(k + " : " + typeof(o[k]));
}

EnumProp(myGlob al); // same result with "this"
Function AddVar() works properly - the global variable is created. This
is, however, quite useless, because same behaviour can be invoked in
simpler way.

Function EvalCode() will not work for function declaration, but it will
work for assigning a function literal to new (global) variable (which is
variable rather than function definition).

EnumProp() is used to enumerate all defined variables and shows that
TestEval2() has been defined, however TestEval1() is missing, although
the code execute without error.

My question - anybody can explain where is function TestEval1() and why
it did not become property in intrisic Global object ?

Thank you
Roman
Mar 26 '06 #1
16 3242
Roman Ziak wrote:
....
EnumProp() is used to enumerate all defined variables and shows that
TestEval2() has been defined, however TestEval1() is missing, although
the code execute without error.

My question - anybody can explain where is function TestEval1() and why
it did not become property in intrisic Global object ?


Perhaps you will find some relevant reading at:
http://blogs.msdn.com/ericlippert/ar...04/414684.aspx and
http://blogs.msdn.com/ericlippert/ar...30/475826.aspx

Csaba Gabor from Vienna

Mar 27 '06 #2
Roman Ziak said on 27/03/2006 9:18 AM AEST:
Hello,

there were times when I used to be looking for a way to access
JavaScript Global object similar to those found in VBScript or PHP
($GLOBALS). At present this has only academic value for me. I was doing
research on JavaScript inheritance recently (simplifying it in
particular) and after reading 10.1.1, 10.1.3 and some other sections of
ECMA262 [1] I got a hint on accessing global object from different than
global scope.

Below is my example (please note that the host is WSH, feel free to
change WScript.Echo to your favourite output call):
myGlobal = this;

function AddVar (id, val)
{
myGlobal[id] = val;
}

function EvalCode (code)
{
myGlobal.eval(c ode);
}

AddVar("roman", 100.1);

WScript.Echo("r oman=" + roman);
Where is WScript.Echo() defined? Alert is more generic:

alert("roman=" + roman);

EvalCode("funct ion TestEval1 (x,y) { return x+y; }")
Add the line:

alert(typeof TestEval1);
and get 'function' in Firefox but 'undefined' in IE.


// this fails
//WScript.Echo( "TestEval1(150, 100) = ", TestEval1(150,1 00) );
Replacing WScript.Echo with 'alert':

alert( "TestEval1(150, 100) = " + TestEval1(150,1 00) );
'works' fine in Firefox but fails in IE with 'object expected'.

A function object is created that belongs to the execution context
created by eval(), it should be also added to the global object
referenced by myGlobal. In Firefox it is, in IE it isn't.

My reading of the spec is that IE is wrong here. In regard to eval
code, section 10.2.2 says:

"The scope chain is initialised to contain the same objects, in
the same order, as the calling context's scope chain. This
includes objects added to the calling context's scope chain by
with statements and catch clauses.

"Variable instantiation is performed using the calling context's
variable object and using empty property attributes.

"The this value is the same as the this value of the calling context."

Which means (to me) that any variable added to eval()'s global object
should also be added to the global object of the calling context (i.e.
the global object referenced by myGlobal).

EvalCode("TestE val2 = function (x,y) { return x-y; }")
Here an anonymous function is assigned to the global property TestEval2,
it is equivalent to the same statement without eval():

TestEval2 = function (x,y) { return x-y; };

and almost identical to:

function TestEval2(x,y){ return x-y; }

// this passes
WScript.Echo( "TestEval2(150, 100) = ", TestEval2(150,1 00) );
The fact that is works in IE shows that sometimes it does follow the
spec. ;-)


function EnumProp (o)
{
for(var k in o)
WScript.Echo(k + " : " + typeof(o[k]));
}

EnumProp(myGlob al); // same result with "this"
Function AddVar() works properly - the global variable is created. This
is, however, quite useless, because same behaviour can be invoked in
simpler way.
Yes.

Function EvalCode() will not work for function declaration, but it will
work for assigning a function literal to new (global) variable (which is
variable rather than function definition).
It does 'work' for a function declaration in some browsers.

EnumProp() is used to enumerate all defined variables and shows that
TestEval2() has been defined, however TestEval1() is missing, although
the code execute without error.
Which says that TestEval1() was created in IE, but was added to the
temporary execution context created by calling eval(). It is added to
myGlobal in Firefox, but not IE.

My question - anybody can explain where is function TestEval1() and why
In IE, TestEval1 was not added to the global object so who know where it
is? It may still exist, but maybe not.

it did not become property in intrisic Global object ?


Because IE is buggy in this regard?
--
Rob
Mar 27 '06 #3
Csaba Gabor said on 27/03/2006 10:31 AM AEST:
Roman Ziak wrote:
...
EnumProp() is used to enumerate all defined variables and shows that
TestEval2() has been defined, however TestEval1() is missing, although
the code execute without error.

My question - anybody can explain where is function TestEval1() and why
it did not become property in intrisic Global object ?

Perhaps you will find some relevant reading at:
http://blogs.msdn.com/ericlippert/ar...04/414684.aspx and
http://blogs.msdn.com/ericlippert/ar...30/475826.aspx


Bizarre - try this;

// Get a reference to the global object
var Global = this;

// Declare fred with function declaration
function fred(){alert('H i from fred');}

// Test it
findFred('Decla ration');

// Declare fred with function expression
var fred = function(){aler t('Hi from fred');}

// Test it
findFred('Expre ssion');

// 'Declare' fred with eval
var fred = eval("function( ){alert('Hi from fred');}");

// Test it
findFred('Eval( )');

function findFred(txt){
var msg = txt + ": fred not found :-(";
for (var p in Global) {
if ('fred' == p) msg = txt + ': found ' + p + '!';
}
alert('fred is ' + (typeof fred) + '\n' + msg);
}

--
Rob
Mar 27 '06 #4
Hi Rob,

I did some more exploration and tests and reading on the articles Csaba
posted. It is more clear now - the way I was expecting it to work is
correct.

RobG wrote:
Roman Ziak said on 27/03/2006 9:18 AM AEST:
<snip>

WScript.Echo("r oman=" + roman);
Where is WScript.Echo() defined? Alert is more generic:


alert is annoying. For those who will follow-up on this issue, here is
better alternative, which will work in both hosts - WSH and browser
(tested with IE/FF/Opera).

if(this.WScript != null)
{
// Why cannot just assign echo = WScript.Echo ... ?
echo = function(s)
{
WScript.Echo(s) ;
}
}
else
{
echo = function(s)
{
s = s ? s.replace(/\n/, "<br/>") : "";
s += "<br/>";
document.body.i nnerHTML += s;
}
}

EvalCode("funct ion TestEval1 (x,y) { return x+y; }")


Add the line:

alert(typeof TestEval1);
and get 'function' in Firefox but 'undefined' in IE.

alert( "TestEval1(150, 100) = " + TestEval1(150,1 00) );
'works' fine in Firefox but fails in IE with 'object expected'.


Yes, this works as expected in FF/Opera and function is added. Seems
that JScript lacks conformance to ECMA-262 here. Also the links, Csaba
posted, confirm it.

When I changed EvalCode() to run eval() in the context of EvalCode()
instead of myGlobal, the function TestEval1() disapeared from global
context as expected (FF/Opera at least).

The funny thing about JScript is that eval execution context is quite
weird, say I do this:

EvalCode("funct ion TestEval1 (x,y) { return x+y; } EnumProp(this); ")

still do not get TestEval1 enumerated in EnumProp().
EvalCode("TestE val2 = function (x,y) { return x-y; }")
Here an anonymous function is assigned to the global property TestEval2, it is equivalent to the same statement without eval():

TestEval2 = function (x,y) { return x-y; };

and almost identical to:

function TestEval2(x,y){ return x-y; }

// this passes
WScript.Echo( "TestEval2(150, 100) = ", TestEval2(150,1 00) );


This part actually works in FF/Opera as expected. Why do you think this
should not work ?
My question - anybody can explain where is function TestEval1() and why


In IE, TestEval1 was not added to the global object so who know where it
is? It may still exist, but maybe not.

it did not become property in intrisic Global object ?


Because IE is buggy in this regard?


That seems to be the conclusion.

It's a shame for JScript 5.6. Cannot get my example to compile with
JScript.NET to test it, keeps babling something about variables not
being defined and such.

Thanks for your responses

--
Roman
Mar 27 '06 #5
Roman Ziak said on 27/03/2006 1:03 PM AEST:
Hi Rob,

I did some more exploration and tests and reading on the articles Csaba
posted. It is more clear now - the way I was expecting it to work is
correct.

RobG wrote:
Roman Ziak said on 27/03/2006 9:18 AM AEST:
<snip>

WScript.Echo("r oman=" + roman);
Where is WScript.Echo() defined? Alert is more generic:

alert is annoying. For those who will follow-up on this issue, here is
better alternative, which will work in both hosts - WSH and browser


Yes, I usually write messages to the document too, but alert is just so
convenient... sometimes.

[...]
The funny thing about JScript is that eval execution context is quite
weird, say I do this:

EvalCode("funct ion TestEval1 (x,y) { return x+y; } EnumProp(this); ")

still do not get TestEval1 enumerated in EnumProp().


It seems that in IE functions are either added to some special object
other than the global object or as "DontEnum".

Try declaring a function:
function fred(){alert('h i from fred');}
You will not find 'fred' using for..in (e.g. your EnumProp()) - try my
response to Csaba Gabor.
[...]
// this passes
WScript.Echo( "TestEval2(150, 100) = ", TestEval2(150,1 00) );

This part actually works in FF/Opera as expected. Why do you think this
should not work ?


I didn't say it wouldn't, I just said that it works in IE - that it
works in other browsers is a given.

This fails in Netscape and IE:

// fred with eval expression
var fred = eval("function( ){alert('Hi from fred');}");
fred();
But does it matter? Is there any circumstance where that might be
required, considering the equivalent and more reliable:

var fred = new Function("alert ('Hi from fred');");
works everywhere? Well, in IE, Firefox and Netscape at least and I
would be very surprised if not elsewhere too.
[...]
--
Rob
Mar 27 '06 #6
VK

Roman Ziak wrote:
Hello,

there were times when I used to be looking for a way to access
JavaScript Global object similar to those found in VBScript or PHP
($GLOBALS). At present this has only academic value for me. I was doing
research on JavaScript inheritance recently (simplifying it in
particular) and after reading 10.1.1, 10.1.3 and some other sections of
ECMA262 [1] I got a hint on accessing global object from different than
global scope.


<snip>

You may find interesting reading my posts in the thread
<http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/11e9e7898e4b6dd 0/07008e34b955519 4>

Also see some references to MSDN linked in my posts.

Briefly IE's scope structure differs rather significally from the one
proposed in ECMA 262 or implemented by say in Firefox.

In your own samples you never work with the Global scope: you are
addressing Window scope allocated atop of Global (again - it's in IE,
not in ECMA specs).

Keeping it in mind the rest of results is easy to explain.

Mar 27 '06 #7
On 27/03/2006 00:18, Roman Ziak wrote:

[snip]
myGlobal = this;
Variables should always be declared using a var statement. Though this
particular assignment is not likely to ever cause problems, it's good
practice to explicitly declare myGlobal.

[snip]
function EvalCode (code)
{
myGlobal.eval(c ode);
}
This is a problem, and seems to also produce different results in
different browsers. The first issue is that you are calling the eval
function as a method, however:

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 MemberExpressio n in a
CallExpression) , or if the eval property is assigned to, an
EvalError exception may be thrown.

-- 15.1.2.1 eval(x), ECMA-262 3rd Ed.

Calling the function as a method seems to cause Firefox and Opera to
violate 10.2.2, whereas IE continues to follow it regardless.

[snip]
Function EvalCode() will not work for function declaration,
It works perfectly, but it doesn't create a global variable (in IE, and
Fx and Op when eval is called as a function). It's not supposed to.

Section 10.2.2 of ECMA-262 states:

When control enters an execution context for eval code, the
previous active execution context, referred to as the calling
context, is used to determine the scope chain, the variable
object, and the this value.

In this case, the calling context is the EvalCode function. Evaluating a
function declaration within that context is /almost/ the same as writing:

function EvalCode(code) {
function TestEval1(x, y) {
return x + y;
}
}

That is, evaluation of the code creates a nested function.

I said 'almost the same' because, as you should know, the variable
instantiation process would have function declarations evaluated before
execution of the code begins. That is, TestEval1 would be available as a
nested function at any point within the body of EvalCode. However,
because the function declaration is evaluated using eval, it doesn't
exist until execution of that function call. It's closer to:

function EvalCode(code) {
var TestEval1 = function(x, y) {
return x + y;
};
}

but still not exactly the same as this would create a local variable
during the variable instantiation process.
but it will work for assigning a function literal to new (global)
variable (which is variable rather than function definition).


For comparison, this evaluation would produce the equivalent of:

function EvalCode(code) {
TestEval2 = function(x, y) {
return x - y;
};
}

Notice that this version does not include a var statement.

The variable, TestEval2, does not exist anywhere within the scope chain
of the EvalCode function, therefore assignment will proceed (as normal)
by creating a new global variable, and assigning to it a reference to
the new function object.

I hope that helps,
Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 27 '06 #8
On 27/03/2006 08:10, VK wrote:

[snip]
You may find interesting reading my posts in the thread [url snipped]


Indeed the OP might. He would then realise, by reading the other posts
in that thread, that you are not the one to listen to when it comes to
technical matters.

Incidentially, I can think of nothing in that thread that is relevant, here.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 27 '06 #9
On 27/03/2006 01:37, RobG wrote:

[snip]
A function object is created that belongs to the execution context
created by eval(), ^^^^^^^
No, not created by eval: used by eval.

If there is an active execution context when the eval function is
called, which there always will be if it is called within the body of a
function, the eval function will use that execution context for its
scope chain, variable instantiation, and this operator value.

If there is no active execution context, then the eval function will act
as if it were global code. The scope chain will consist only of the
global object, variable instantiation will occur using the global
object, and the this operator will refer to the global object.
it should be also added to the global object referenced by myGlobal.
[...]
No, it shouldn't. See my other post.
My reading of the spec is that IE is wrong here.
On the contrary. IE is acting precisely to specification, and Opera and
Firefox will, too, if the eval function is called as a function (as it
should be):

var global = this;

function evalAsMethod(co de) {
global.eval(cod e);
}
function evalAsFunction( code) {
eval(code);
}

evalAsFunction( 'function test() {}');
alert(typeof test); /* undefined */

evalAsMethod('f unction test() {}');
alert(typeof test); /* function (in Op and Fx) */

[snip]
Which means (to me) that any variable added to eval()'s global object
should also be added to the global object of the calling context (i.e.
the global object referenced by myGlobal).


You seem to have muddled the definition of execution context. It is,
more-or-less, the environment for a function; it's scope chain, variable
object, and this operator value. An execution context is formed just by
calling a function, not how it is called (though that can affect facets
of the execution context). Therefore, the calling context (if any) is
the execution context of the function in which the eval function is called.

The eval function only acts as global code when executed in the global
portion of a program.

[snip]

The rest of your post seems to be based on this (unfortunately mistaken)
premise.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 27 '06 #10

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

Similar topics

10
6732
by: Andy Fish | last post by:
Hi, can anybody put forward a sensible argument javascript's behaviour of creating a new global variable whenever I assign to a previously undeclared variable. I can't beleive this is just for the sake of convenience (surely we learned this much from basic). here's my proposal: all "global" (document scope) variables must be declared by 'var' outside a function block.
7
7442
by: Kevin Newman | last post by:
I've been toying with a namespace manager, and wanted to get some input. So what do you think? if (typeof com == 'undefined') var com = {}; if (!com.unFocus) com.unFocus = {}; com.unFocus.Namespaces = new function() { this.register = function(namespace) { namespace = namespace.split('.');
2
3066
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is what I'm hoping to achieve. I've never before had to use Javascript closures, but now I do, so I'm making an effort to understand them. I've been giving this essay a re-read: http://jibbering.com/faq/faq_notes/closures.html
1
25714
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that variable can only be used in that function. If you were to try to access that variable anywhere else in...
20
2320
by: shapper | last post by:
Hello, How to create a namespace in Javascript containing two methods? And how to access those methods? Thanks, Miguel
0
9762
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
11057
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
10384
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...
1
7932
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
7094
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
5761
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
5958
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4575
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
4174
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.