473,412 Members | 4,519 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,412 software developers and data experts.

a variable "a" and "window.a" ??

i saw a code refactorying onload event listener
window.onloadListeners=new Array();
window.addOnLoadListener=function(listener) {
window.onloadListeners[window.onloadListeners.length]=listener;
}
why declare the onloadListeners, addOnLoadListener below window?

i think bare "afunc" and "window.afunc" are same thing and available
both way.

is there a difference?

Jan 26 '07 #1
11 2188
On Jan 26, 12:51 pm, "gg9h0st" <mn9h...@hotmail.comwrote:
i saw a code refactorying onload event listener

window.onloadListeners=new Array();
window.addOnLoadListener=function(listener) {
window.onloadListeners[window.onloadListeners.length]=listener;

}why declare the onloadListeners, addOnLoadListener below window?

i think bare "afunc" and "window.afunc" are same thing and available
both way.
That's correct, |window| is the global object, so all global
variables/functions are properties on |window| and vice versa.
>
is there a difference?
Assigning to window.prop specifically can be useful when you want to
dynamically create a global variable/function.

Or if you have a local variable with the same name, hiding the global
variable, accessing the global can be done via |window|.

Nickolay

Jan 26 '07 #2
In article <11**********************@j27g2000cwj.googlegroups .com>,
Nickolay Ponomarev <as*******@gmail.comwrites

<snip>
>That's correct, |window| is the global object,
<snip>

Except when there isn't a window.

John
--
John Harris
Jan 26 '07 #3
VK
On Jan 26, 12:51 pm, "gg9h0st" <mn9h...@hotmail.comwrote:
i saw a code refactorying onload event listener

window.onloadListeners=new Array();
window.addOnLoadListener=function(listener) {
window.onloadListeners[window.onloadListeners.length]=listener;

}
I see no refactoring here because onloadListeners is not an intrinsic
event listener (window.onload is) Someone is just making a friendly
onload dispatcher - when several functions have to be called on the
same event in some pre-defined order.
why declare the onloadListeners, addOnLoadListener below window?
I'm not the author so I can only guess: it is a personal preference
matter I say. It would use var onloadListeners=new Array(); but nothing
criminal in the way above.
i think bare "afunc" and "window.afunc" are same thing and available
both way.
is there a difference?
For the majority of cases you can consider it as true - because either
window.a and a will act the same.
In the reality window is a separate host object placed before Global,
where Global is always at the end of the scope chain. Of course in case
of window-less context window host object is not presented at all.
Again, for the majority of cases you may disregard this detail. It gets
very important though in some particular circumstances, say when you
want to protect your script from Greasemonkey-like programs and overall
to ensure de-maskoned environment.
<http://groups.google.com/group/comp.lang.javascript/msg/65a858c19f383df0>

P.S. I neither support nor fight Greasemonkey, magicFunction and
similar run-time content refactoring tools. Sometimes though it is
important to ensure that everything will work and look exactly as it
was intended or better do not work at all.

Jan 26 '07 #4
VK wrote:
<snip>
In the reality window is a separate host object placed
before Global, where Global is always at the end of the
scope chain.
<snip>

You have spewed this nonsense before, and have been asked, and declined,
to back it up with some (any) evidence. You may recall that when tested
no evidence was found that supported your assertion:-

<URL:
http://groups.google.com/group/comp....912f3965710e5d
>


- although it is clear from that thread that you did not understand the
scope chain in javascript and so could not comprehend how the test shown
demonstrated your assertion false.

Richard.

Jan 28 '07 #5
On Jan 26, 4:51 am, "gg9h0st" <mn9h...@hotmail.comwrote:
i saw a code refactorying onload event listener

window.onloadListeners=new Array();
window.addOnLoadListener=function(listener) {
window.onloadListeners[window.onloadListeners.length]=listener;

}why declare the onloadListeners, addOnLoadListener below window?

i think bare "afunc" and "window.afunc" are same thing and available
both way.

is there a difference?
My saying about this matter is that, overloading the window object
with global properties is plain stupid. Even if window.aFunc is the
same as var aFunc (or function aFunc), the point is not really there ;
any implementation should be placed in their own namespace (or class).
For example, an event handler system should be implemented in a class
Object like Event, then have all properties and functions attached
directly to it.

Of course, Event would be a property of the window object, but that
ressemblance would stop there, as other attributes and properties
would all be in a specific classification. (Hence the name 'class'.)
Javascript might be an interpreted language, but it is also an object
oriented one ; programmers should think like so and stop writing
programs like if it were procedural (like BASIC).

This technique not only ensure having a better readable code (where
everything is not piled up at the same place, but in a human
comprehensive way, or hierarchy), but it also ensure expandable code
that will not break down due tu variable / function conflicts with
other third party scripts or libraries. Even if it's only for a small
project, reusable code concept save time, creates good coding habbits,
make the code well structured, etc.

Now, to come back to the original matter, you should read about
"variable context" in Javascript ; you'll notice that "var a" is not
always the same thing as "this.a", or in other words, "var
onloadListeners=new Array();" is not always the same thing as
"window.onloadListeners=new Array();" (I would personally prefer this
syntax : "window.onloadListeners=[];"). (see http://devedge-
temp.mozilla.org/library/manuals/2000/javascript/1.5/reference/
stmt.html#1066604).

If you are outside a function (or class), "var a = 1;" is the same as
"a = 1;" (hence the same as "window.a = 1;").

Inside a function, "var a = 1;" is called a local variable. Executing
only "a = 1;" inside a function will throw a warning saying that "a"
hasn't been declared. Unlike Java, accessing a class variable requires
the "this" keyword".

Here's an example script that illustrate the fonctionality :

var test = 1;
alert( test ); // 1

window.test++;
alert( test ); // 2

this.test++;
alert( test ); // 3

// this is the same as var Test = function() ...
// or this.Test = function() ...
function Test() {
this.test = 100; // class variable
}

Test.prototype = {

// this is the same as Test.prototype.printTest =
function()...
printTest: function() {
alert( test ); // undefined
test++;
alert( test ); // NaN (should be accessed with this.test)

var test = 1; // local variable

alert( test ); // 1
test++;
alert( test ); // 2

this.test++;
alert( this.test ); // 101
}
};

var test = new Test();
test.printTest();

So, I hope that you see the idea behind having your functions and
methods well structured. Please code responsibly :)

-Yanick

Jan 29 '07 #6
VK
In the first part you instantiate variable temp with numeric value and
you show that in the global namespace
temp
window.temp
this.temp
can be considered the same in casual circumstances. That is correct.

After that you override global variable temp with an instance of Temp
object, so the previous value is irrelevant. Now
temp
window.temp
this.temp
will point to that instance and alert(temp) will show the result of
toString method for an object instance, "object [Object]" string or
whatever is set for toString. It doesn't prove anything above of what
you demonstrated in the first part.

The sample has to be corrected though a bit, because in the local
scope of printTest method you have var test declared, so alert(test)
shows "undefined". In JavaScript all var statements executed before
starting the execution flow with instantiation of var identifiers with
undefined value. This way local variable temp already exists and it
has value undefined at the moment of execution of alert(temp) -
despite the explicit temp initialization located below alert(temp)
statement. Programmatically it is called "shadow global variable with
a local one". The corrected sample would be:
function Test() {
this.test = 100;
}
Test.prototype = {
'printTest' : function() {
alert(test)
}
};
var test = new Test();
test.printTest();

It is not in direct connection of a vs window.a in global namespace IMO

Jan 29 '07 #7
VK
On Jan 29, 8:06 pm, "VK" <schools_r...@yahoo.comwrote:
<snip>
It is not in direct connection of a vs window.a in global namespace IMO
But it is a valuable well-illustrated warning that in a local
namespace a=something and window.a = something may lead to assignments
to all different objects. So sorry if I sounded as decreasing the
value of your post.

Actually within a local scope window is the tool to be able to address
both global and local variables with the same name (if such necessity
exists):

<script>
var v = 1;

function f() {
var v = 2;
alert(v);
alert(window.v);
}

f();
</script>

Jan 29 '07 #8
On Jan 29, 5:22 pm, "Yanick" <yanick.roc...@gmail.comwrote:
On Jan 26, 4:51 am, "gg9h0st" <mn9h...@hotmail.comwrote:
[snip]
Now, to come back to the original matter, you should read about
"variable context" in Javascript ; you'll notice that "var a" is not
always the same thing as "this.a", or in other words, "var
onloadListeners=new Array();" is not always the same thing as
"window.onloadListeners=new Array();" (I would personally prefer this
syntax : "window.onloadListeners=[];"). (seehttp://devedge-
temp.mozilla.org/library/manuals/2000/javascript/1.5/reference/
stmt.html#1066604).
Any reasons you don't link to the migrated reference on
developer.mozilla.org instead? The devedge-temp is just a temporary
mirror of old devedge content, it's not maintained and is not
guaranteed to exist..
If you are outside a function (or class), "var a = 1;" is the same as
"a = 1;" (hence the same as "window.a = 1;").

Inside a function, "var a = 1;" is called a local variable. Executing
only "a = 1;" inside a function will throw a warning saying that "a"
hasn't been declared. Unlike Java, accessing a class variable requires
the "this" keyword".
Unlike Java, there is not concept of 'class' in JS yet :)

You should have mentioned that the way |this| work might be a bit
counter-intuitive for those unfamiliar with JS:
http://developer.mozilla.org/en/docs/
Core_JavaScript_1.5_Reference:Operators:Special_Op erators:this_Operator
#Method_binding

[snip]
// this is the same as var Test = function() ...
// or this.Test = function() ...
function Test() {
Not exactly - this is a function declaration that declares a named
function, while the other two are function expressions assigned to a
variable/property. The difference is described here:
http://developer.mozilla.org/en/docs/
Core_JavaScript_1.5_Reference:Functions#Function_c onstructor_vs._functi
on_declaration_vs._function_expression

[snip the rest of the message]

Nickolay

Jan 30 '07 #9
On Jan 30, 10:32 am, "Nickolay Ponomarev" <asquee...@gmail.com>
wrote:
[...]
Any reasons you don't link to the migrated reference on
developer.mozilla.org instead? The devedge-temp is just a temporary
mirror of old devedge content, it's not maintained and is not
guaranteed to exist..
Well, no reason, really, it's just the first link that Google
returned :) Since I have no need to keep such basic documentation
around, I simply did a simple Google and returned the first context-
related entry. Sorry if there are better references.
Unlike Java, there is not concept of 'class' in JS yet :)
True. I meant "Object". Though, technically, even if the concept of
'class' is not present (documented) in the language, using 'new' to
call function consctructors is in definition creating a new instance
of a custom object. Isn't that also the definition of creating an
instance of a custom class ? I may be misitaking, but the ressemblance
is pretty close. Though I agree to say that it is wrong to call
'class' what is not truly one.

Also, perhaps my example did lack of precision, whenever a 'var'
instruction is found in a script, even if further down the actual
executed line, that variable will be undefined (this is why there
cannot be two 'var test;' declaration in the same context) So, by
removing the 'var test;' declaration in the function printTest, the
first alert( test ); would print {Object: object} ; it is, in fact,
pointing to the global 'test' because no local variable of that name
is found locally, so it goes 'up one context'. (if I may say)

Despite it all, my point of view still stands ; only fools bind every
declarations to the window object.

-Yanick

Jan 30 '07 #10
Yanick wrote:
On Jan 30, 10:32 am, Nickolay Ponomarev wrote:
<snip>
>Unlike Java, there is not concept of 'class' in JS yet :)
And with continuing good fortune there never will be.
True. I meant "Object". Though, technically, even if the
concept of 'class' is not present (documented) in the
language, using 'new' to call function consctructors is
in definition creating a new instance of a custom object.
Isn't that also the definition of creating an instance
of a custom class ?
Not really. In a class based language a class is fixed by its definition
before the code executes, and all object instances created with a
constructor are or the same 'type' (in the sense that they all have the
same methods and properties/fields/members). In javascript using - new -
with a function does not guarantee that each object created will have the
same properties and methods, and once created any object can have its
properties and methods swapped/modified/removed.

It is still possible to implement the 'class' concept in javascript (and
there are many more ways of instantiating object of a 'class' than just
using - new - on a constructor function), but in order to employ the
concept you have to treat the 'class' definition as fixed and the object
instances employed as immutable (in form, not with regard to the data
they hold) (not at all difficult as you just don't set about modifying
them at run time).

It is not at all difficult to employ the 'class' concept when designing
and implementing javascript programs, but the bottom line is that such a
concept is imposed upon the resulting code by the programmer and is not
part of the language. And it is useful to remember where these things are
coming from, not least because that makes it easier to see that there are
many more choices available, and so decisions to make, when using
javascript than are on offer in class based languages.
I may be misitaking, but the ressemblance is pretty close.
Though I agree to say that it is wrong to call 'class' what
is not truly one.
If code implements the 'class' concept (by design) then I have no trouble
referring to the result as a class.
Also, perhaps my example did lack of precision, whenever a 'var'
instruction is found in a script, even if further down the actual
executed line, that variable will be undefined (this is why there
cannot be two 'var test;' declaration in the same context)
<snip>

There can be as many - var test; - statements within the same context as
you like. There is little point in having more than one, but the language
allows more and is very clear on how they will be handled.

It is even not uncommon to see the same Identifier declared as a counter
in multiple - for - statements within the same function. I am not
particularly in favour of that but reasonable justifications have been
presented for its being a good (or at least valid) practice.

Richard.

Jan 30 '07 #11
On Jan 30, 9:30 pm, "Yanick" <yanick.roc...@gmail.comwrote:
On Jan 30, 10:32 am, "Nickolay Ponomarev" <asquee...@gmail.com>
wrote:
Unlike Java, there is not concept of 'class' in JS yet :)

True. I meant "Object". Though, technically, even if the concept of
'class' is not present (documented) in the language, using 'new' to
call function consctructors is in definition creating a new instance
of a custom object. Isn't that also the definition of creating an
instance of a custom class ? I may be misitaking, but the ressemblance
is pretty close. Though I agree to say that it is wrong to call
'class' what is not truly one.
I was just nit-picking, your example was good. When comparing JS to
Java it's better to avoid mentioning JS classes to avoid unnecessary
confusion :)

Nickolay

Jan 30 '07 #12

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

Similar topics

3
by: Bob | last post by:
I usually use some "pre-load" code in my pages to preload graphics that will be swapped. But, I'm thinking that rather than the long, repetitive, once, for each graphic hardcoded stuff like this: ...
3
by: JohnEGee | last post by:
Hello, all, and TIA for any help you can offer. I've searched the Internet for answers and have finally come here. I've created a page (several, actually) with a link that opens a pop-up...
22
by: stephen | last post by:
I have created an order form that users javascript to create a new html document when the customers clicks the "print page" button. Once the new document has been created it then prints the...
5
by: lindanr | last post by:
In ASP.NET 2005 I have an onblur="window.close()" javascript event in the <body> tag. When I click on the window's scrollbar, the window closes. The same code works fine in ASP.NET 2003. Any...
1
by: kbarrios | last post by:
Hi, I am working with VBScript and I put a "window.open" inside a "form action post" due that I am handing a "checkbox" on it, but the "window.open" doesn't work: <FORM...
4
by: jodleren | last post by:
Hi all I have a file I open in a smaller window, like this: <a href="#" onclick="window.open.... but it also causes the main window to jump to the top. What have people done to avoid that?...
6
by: =?ISO-8859-1?Q?Une_B=E9vue?= | last post by:
i'd like to intercept the window.onload event in order to distribute it, as needed, to several methods. example : suppose i have several methods doing unlinked initialisations: ...
5
by: anEchteTrilingue | last post by:
Hi everybody. Thank you for reading my post. I am having trouble getting "this" to work in all versions of IE (it's fine in Firefox, opera, konqueror, etc). What I would like to do is add an...
24
by: Jeremy J Starcher | last post by:
While reading c.l.j, I've noticed that some people prefer and indeed even recommend the use of "window.alert()" over "alert()". I can't find any technical reason to make this distinction, and...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
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...

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.