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

G

gg9h0st

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?
 
N

Nickolay Ponomarev

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
 
V

VK

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.
 
R

Richard Cornford

VK wrote:
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.lang.javascript/msg/d1912f3965710e5d


- 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.
 
Y

Yanick

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
 
V

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
 
V

VK

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>
 
N

Nickolay Ponomarev

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_Operators: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_constructor_vs._functi
on_declaration_vs._function_expression

[snip the rest of the message]

Nickolay
 
Y

Yanick

[...]
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
 
R

Richard Cornford

Yanick said:
On Jan 30, 10:32 am, Nickolay Ponomarev wrote:

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.
 
N

Nickolay Ponomarev

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
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top