n00b questions for javascript!

D

disappearedng

Hi everyone
I came from Java so there's somethings that I would like to clear up:

1) What's the purpose of var? Since JS has no "forced types" (i don't
know if I am using the right term), why do we bother to declare a
variable like
var a;
a = 1;
when we can simply just do this?
a = 1; (without implicitly declaring var a before hand?)

2) When do we use new? In Java, we use new when we are constructing a
new class that has a constructor. But in Javascript, I don't think I
have come across the concept of "classes".
For example,
//constructor, (still a function)
function Jar(param){
this.member = param;
}

why is it such that I have to use the following:
var myJar = new Jar('abc'); //Note that this requires "new" here
in order to declare this?
Note that var myJar = Jar('abc') doesn't work.

3) This question actually refers to a particular writer's JS
If you have time please look at this.

function Container(param) {

function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}

this.member = param;
var secret = 3;
var that = this;
}

According to the author,
"The private method dec examines the secret instance variable. If it
is greater than zero, it decrements secret and returns true. Otherwise
it returns false. It can be used to make this object limited to three
uses."

My question is: How do you access dec()?
I tried using
var myContainer = new Container('abc');
myContainer.dec() doesn't work!

Thx man
 
G

Gregor Kofler

disappearedng meinte:
1) What's the purpose of var? Since JS has no "forced types" (i don't
know if I am using the right term), why do we bother to declare a
variable like
var a;
a = 1;
when we can simply just do this?
a = 1; (without implicitly declaring var a before hand?)

var defines a variable as local.
2) When do we use new? In Java, we use new when we are constructing a
new class that has a constructor. But in Javascript, I don't think I
have come across the concept of "classes".

Pretty good. Some JavaScript experts still do have problems with that.
For example,
//constructor, (still a function)
function Jar(param){
this.member = param;
}

The meaning of "this" changes. It's replaced by the new object.
why is it such that I have to use the following:
var myJar = new Jar('abc'); //Note that this requires "new" here
in order to declare this?
Note that var myJar = Jar('abc') doesn't work.

Because "this" in Jar() still points to wherever it pointed before
invoking the function().

Take a look at
http://javascript.crockford.com/survey.html
This should make everything clear.
3) This question actually refers to a particular writer's JS
If you have time please look at this.

function Container(param) {

function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}

this.member = param;
var secret = 3;
var that = this;
}

According to the author,
"The private method dec examines the secret instance variable. If it
is greater than zero, it decrements secret and returns true. Otherwise
it returns false. It can be used to make this object limited to three
uses."

My question is: How do you access dec()?
I tried using
var myContainer = new Container('abc');
myContainer.dec() doesn't work!

No. dec() can only be called within Container(). It's a private function.

Add
this.dec = dec;
to Container, and you can access it as a (public) method of Container.

Gregor
 
M

Martin Rinehart

Another reason to use var:

function foo( args ) {
i = 5;
...
}

You'd expect 'i' to be local in foo(). It's not. It's scope is global.

function bar( args ) {
var i = 5;
...
}

That 'i' is local in bar().
 
M

Martin Rinehart

One other point (from a fellow refugee from JavaLand) "new" is very
Java, not so very JavaScript.

var person = new Person( 'Fred', 'Latham' ); // JavaLand style

var person = { firstName:'Fred', lastName:'Latham' }; // JavaScript,
or

var person = {} // object, no attrs
person.firstName = 'Fred';
person.lastName = 'Latham';

var another = {};
another.prototype = person; // another now shares person's attrs and
their values
another.occupation = 'JavaScripter'; // another now extends the object

// method shared by both:
person.prototype.wholeName = function() { return this.firstName + ' '
+ this.lastName; }

You probably want to buy Crockford's book to get going in the right
direction.
 
H

Henry

Hi everyone
I came from Java so there's somethings that I would like to
clear up:

1) What's the purpose of var?

To declare a variable. Java is block scoped, javascript is not, and
its scoping units are functions. A variable declared inside a function
body is only visible to code inside (lexically inside) the same
function (the code of the function's body, including any nested
functions).
Since JS has no "forced types"
(i don't know if I am using the right term), why
do we bother to declare a variable like
var a;
a = 1;

Given that code, "we" would write - var a = 1; - as there is little
point in splitting it up there.
when we can simply just do this?
a = 1; (without implicitly declaring var a before hand?)

Assignments to undeclared Identifiers result in the creation of
properties of the global object. These may, in most relevant senses,
act as global variables (properties of the global object added by
executing code can be deleted, while real global variables cannot
(people don't tend to attempt to delete global variables so the
practicalities of deleting don't have much impact)).

There is a general programming axiom that things should never be given
more scope than they need, so creating what are effectively global
variables where function local variables could be used would be a bad
idea. And certainly introduces considerable additional potential for
naming conflicts. Consider, for example, a loop counter which in java
would traditionally be named "i", and a loop that included a call to a
function that also executed a loop with a counter named "i". If the
two "i"s were global then the loop counter for the first loop would be
being modified by the loop code in the function it called.

It may then be argued that global variables do not need to be
declared. There are two reasons for not doing that: the first is code
maintainability/understandably; you encounter - a = 1; - in function
body code and wonder if the intention is to assign to a global
variable or whether this is an example of failing to declare - a - as
a function local variable. If you find a global - var a; - declaration
then you know the intention, otherwise you have to look for other uses
of/references to a global - a - (and if there are none that implies
looking at all the code before that can be determined).

The second reason for declaring all global variables is a peculiarity
of IE browsers. If an Element in the DOM is given an ID attribute, say
- ID="a", and there is no declaration of a correspondingly named
global variable, then IE creates a property of the global/window
object with a name that corresponds to the ID attribute's value.
Having created this, effectively, global variable to refer to the DOM
Element it then throws exceptions if you attempt to assign to that
variable. So, in this example, - a = 1; - would result in an exception
being thrown. If you declare - var a; - globally IE does not assign
the Element reference to that variable, and does not throw exceptions
if you assign to it.

Apart from being quite difficult to track down, this IE issues makes
javascript code vulnerable to modifications in HTML. If you are using
a non-declared global variable and someone else modifies the HTML
(which is not unknown in collaborative projects) such that they
introduce an element with an ID attribute that happens to coincide
with that global variables then the script suddenly breaks, but only
in IE.
2) When do we use new? In Java, we use new when we are
constructing a new class that has a constructor. But in
Javascript, I don't think I have come across the concept of
"classes".

Not as part of the language. The concept of 'class' can be employed in
(OO) code design.
For example,
//constructor, (still a function)
function Jar(param){
this.member = param;

}

why is it such that I have to use the following:
var myJar = new Jar('abc'); //Note that this
requires "new" here
in order to declare this?

Applying the - new - operator to a function causes a new object to be
created, the (current) value of the function's - prototype - property
to be assigned to the new object's internal [[Prototype]] property
(for use as the start of its prototype chain), and then for that
function's body to be executed with the - this - value assigned a
reference to the new object (and if the function's body does not
return any other object reference then the result of the - new -
expression is a reference to that newly created object). The reason
for using the - new - operator is that you want these things to
happen, and you use it when you want these things to happen.
Note that var myJar = Jar('abc') doesn't work.

Well, it does work, it just doesn't do anything expected/useful. In
that case the - this - value for the execution of the function is a
reference to the global object (so a "member" property is added to the
global object) and as the function has no return statement the result
of the call expression is the undefined value.
3) This question actually refers to a particular writer's
JS If you have time please look at this.

function Container(param) {

function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}

this.member = param;
var secret = 3;
var that = this;

}

According to the author,
"The private method dec examines the secret instance
variable. If it is greater than zero, it decrements
secret and returns true. Otherwise it returns false.
It can be used to make this object limited to three
uses."

My question is: How do you access dec()?

In that code you cannot access it. Indeed, the function object
resulting form the function declaration for - dec - will be garbage
collected (probably soon) after the constructor finishes execution.
I tried using
var myContainer = new Container('abc');
myContainer.dec() doesn't work!

No, it wouldn't. Given only the code above the object that results
form the - new - expression will have no "dec" property, and so
attempting to call - myContainer.dec - will error.
 
K

Kenny

These JS frameworks are death by a thousand cuts. Dojo is 300k
compressed and I am still building. And lots of lame code out there,
they cannot even follow the simplest HIG principles.

Trying to talk the boss into letting me just do HTML/CSS/JS and start
enjoying programming again.

Thx for priming the pump, anyway.

cheers, kenny
 
J

John G Harris

2) When do we use new? In Java, we use new when we are constructing a
new class that has a constructor. But in Javascript, I don't think I
have come across the concept of "classes".

You use 'new' to create an object, not a class. This is just as true in
Java as in javascript.

In general, a class is the collection of all possible objects that have
something particular in common. In Java you have class definitions,
source text that starts with the keyword 'class', that says what the
objects have in common. The definition can also supply additional
information such as a name for the class.

Javascript is less helpful. You often have to program yourself things
that are done by the compiler in other languages. If you want a class
definition you have to write it yourself in the form of a constructor
function (maybe more than one) and have enough self-discipline to avoid
building a horrible mess.

If you don't need all the facilities that a constructor function can
provide then you may be able to use an object literal instead.

For example,
//constructor, (still a function)
function Jar(param){
this.member = param;
}

why is it such that I have to use the following:
var myJar = new Jar('abc'); //Note that this requires "new" here
in order to declare this?

In Java, myJar holds a pointer to an area in memory that holds the
object's data, etc. 'new' allocates a fresh memory area and arranges for
the constructor to act on that area. From then on you can write myJar
when you really mean thing-pointed-to-by-myJar. The same is true in
javascript.

Note that var myJar = Jar('abc') doesn't work.
<snip>

This doesn't work in Java either. Constructors don't have return type
and so can't be used to assign a value to a variable.

John
 
K

Kenny

Kenny said:
These JS frameworks are death by a thousand cuts. Dojo is 300k
compressed and I am still building. And lots of lame code out there,
they cannot even follow the simplest HIG principles.

Trying to talk the boss into letting me just do HTML/CSS/JS and start
enjoying programming again.

Nope, qooxdoo is the answer. Hides HTML and CSS, very fast,
well-documented, adds a bit of an OO model atop JS's...overall, very
sophisticated.

hth, kenny
 
J

Joost Diepenmaat

Kenny said:
Kenny wrote:
Nope, qooxdoo is the answer. Hides HTML and CSS, very fast,
well-documented, adds a bit of an OO model atop JS's...overall, very
sophisticated.

I'm looking at it, and it's pretty interesting. Not so sure about the
API or the actual implementation (need to look at both some more). It
doesn't seem THAT fast, though.

Cheers,
J.
 
D

David Mark

I have graduated from asking to informing.

Never mind. I see that the question is "name another monstrous blob
of ill-advised browser scripting rubbish."

/**
* Whether the first element contains the second one
*
* Uses native non-standard contains() in Internet Explorer,
* Opera and Webkit (supported since Safari 3.0 beta)
*
* @signature function(element, target)
* @param element {Element} Parent element
* @param target {Node} Child node
* @return {Boolean}
*/
contains : qx.core.Variant.select("qx.client",
{
"webkit|mshtml|opera" : function(element, target)

So if some baseless series of characters contains these strings
(assumes some variant of Safari, IE or Opera), take this fork.

{
if (qx.dom.Node.isDocument(element))

Passing a document to this would seem a waste for most applications.
And who knows what sort of mysticism is used in this "isDocument"
method? Designs that require differentiating between host object
types are doomed to fail (see jQuery.)

{
var doc = qx.dom.Node.getDocument(target);

return element && doc == element;

} else if (qx.dom.Node.isDocument(target))
{
return false;

Waste of code.

}
else
{
return element.contains(target);

Assumes a non-standard method exists. Blows up in anything that looks
remotely like IE, Safari or Opera, but does not implement a "contains"
method on elements.

}
},

// http://developer.mozilla.org/en/docs/DOM:Node.compareDocumentPosition
"gecko" : function(element, target) {

Sure, anything that calls itself "Gecko" must...

return !!(element.compareDocumentPosition(target) & 16);

support compareDocumentPosition!

},

[snip]

Didn't this thing die out years ago? Certainly it should have. It is
the same sort of generalized, over-the-top incompetent rubbish that
has plagued Web applications during this initial craze over Ajax.
 
G

Gregor Kofler

David Mark meinte:
Never mind. I see that the question is "name another monstrous blob
of ill-advised browser scripting rubbish."
Didn't this thing die out years ago? Certainly it should have. It is
the same sort of generalized, over-the-top incompetent rubbish that
has plagued Web applications during this initial craze over Ajax.

Well, you have to credit them that they created a lean 17MB(!) SDK
package... From a brief look, it seems to be a monster in the "extJS"
vein - anyway, JS now has classes. Makes you wonder what Kenny was
babbling about when he stated:

"These JS frameworks are death by a thousand cuts. Dojo is 300k
compressed and I am still building. And lots of lame code out there,
they cannot even follow the simplest HIG principles. "

But then he moved from asking nOOb questions to dishing out advice in
just 8 days.

Gregor
 
K

Kenny

David said:
[snip]

Didn't this thing die out years ago? Certainly it should have. It is
the same sort of generalized, over-the-top incompetent rubbish that
has plagued Web applications during this initial craze over Ajax.

Hey, thanks for taking a look at it, I'll keep my eyes open. Right now
my app runs on Chrome, Safari, and FireFox but not IE.

kt
 
D

David Mark

David Mark meinte:


Well, you have to credit them that they created a lean 17MB(!) SDK
package... From a brief look, it seems to be a monster in the "extJS"

It makes you wonder why people would set out to write these bloated
general-purpose "frameworks" when they are so obviously ill-suited for
browser scripting. Though, it is no wonder that the average Web
developer who wants an "Ajax site" sees them as gold.
vein - anyway, JS now has classes. Makes you wonder what Kenny was
babbling about when he stated:

"These JS frameworks are death by a thousand cuts. Dojo is 300k
compressed and I am still building. And lots of lame code out there,
they cannot even follow the simplest HIG principles. "

No telling.
But then he moved from asking nOOb questions to dishing out advice in
just 8 days.

That's what happens. Download a lousy script, try it in a handful of
browsers, talk to previously indoctrinated ignoramuses, conclude that
this is how browser scripting is done and embark on a career as an
"Ajax expert" with [fill in the framework name] experience. It can be
quite lucrative due to ignorance at the management level and the
constant maintenance that is required to keep one of their "solutions"
working in three browsers.
 
K

Kenny

Joost said:
I'm looking at it, and it's pretty interesting. Not so sure about the
API or the actual implementation (need to look at both some more). It
doesn't seem THAT fast, though.

I'll keep you posted. It just seems a lot zippier on handling a grid
than I experienced under Dojo or YUI or jQuery.

Right now I am trying to figure out why AllegroServe cannot keep web
sessions straight in anything other than FFox (after doing fine a couple
of hours ago <sigh>).

It does mean writing JS where jquery and Dojo supported the declarative
markup model better, I plan eventually to have the declarative thing
going on the Lisp side so its kinda better (but less portable to other
frameworks) to leave the whacky world of html/css behind.

Meanwhile I see these hardcores here want me doing html and css -- I bet
they were the last to let go of assembler, too.

:)

kt
 
K

Kenny

Gregor said:
David Mark meinte:



Well, you have to credit them that they created a lean 17MB(!) SDK
package... From a brief look, it seems to be a monster in the "extJS"
vein - anyway, JS now has classes.

Working out pretty well, too, for what classes do best: divide up huge
wodges of code and even maybe make reuse a little easier.
Makes you wonder what Kenny was
babbling about when he stated:

"These JS frameworks are death by a thousand cuts.

qooxdoo Just Works. If I work for two hours I produce two hours of
application. It has been a while since I experienced that playing with
dojo and yui.
Dojo is 300k
compressed and I am still building.

I gotta confess, a build of my qooxdoo app is now bigger than that!
And lots of lame code out there,
they cannot even follow the simplest HIG principles. "

I am talking about click vs shift-click vs control-click -- the simplest
thing in the world and qooxdoo is the first I have seen that got it right.
But then he moved from asking nOOb questions to dishing out advice in
just 8 days.

I been at this a while, I know quality when I see it. Little things like
the build process, the runtime errors (amazing detail), the slick layout
(nothing else comes close -- well, I did not try them all).

And I like to shoot from the hip. :)

I will come back and confess if it does not work out for us.

cheers, ken
 
D

David Mark

[snip]
Meanwhile I see these hardcores here want me doing html and css -- I bet

That makes no sense. Poorly written "framework" scripts are hardly a
substitute for HTML and CSS.
they were the last to let go of assembler, too.

You still don't get it. People who actually write browser scripts
accumulate repositories of re-usable code. That's what they use to
build Web applications. Those who do not, download other people's
repositories and pray that the authors knew what they were doing (and
will always be there to help them.) The impetus to stick with them is
so strong (anything to remain blissfully ignorant to the rigors of
browser scripting) that some communities "flourish" even after their
leaders have been exposed as clueless windbags (e.g. John Resig.)
Good luck with that. See you back here in a few months with lots of
impossibly complex problems.
 

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,755
Messages
2,569,538
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top