Arrays and object oriented capabilities...

L

Luke

Here is my emails to Danny Goodman (but probably he is very busy so he
didn't answered it).

First email(simple): Subject: JavaScript Arrays
"
We all know the array can act like HashMap, but is there a shortcut
for creating such array ? eg
//simple array indexed via numbers
var a = new Array("a", "fdsf", "sada");
or,
a["a", "fdsf", "sada"];
, bo how a to make it an HashMap ? maybe that:
a["key1":"a", "key2":"fdsf", "key3":"sada"]

As last we all know that it works for objects:
a = { "key1":"a", "key2":"fdsf", "key3":"sada"};

Thanks for answer;
Lukasz(Luke) Matuszewski
"

Second email: Subject: JavaScript advanced elements
"
Hi !
I am a student from Tech. Univ. Of Gdansk and I am sort of advanced
begginer :) in JavaScript and ECMAScript standards. When I was reading
many scripts on different general projects like js calendar or js
menu-realted projects i found many things that i think to understand
but i want to know more about it with also realtion to ECMAScript
standard. Here is the following things:
1. Moder-browsers quick object construction like this:

function DynamicTree(id) {
...
this.img = {
"branch": "tree-branch.gif",
"doc": "tree-doc.gif",
"folder": "tree-folder.gif",
"folderOpen": "tree-folder-open.gif",
"leaf": "tree-leaf.gif",
"leafEnd": "tree-leaf-end.gif",
"node": "tree-node.gif",
"nodeEnd": "tree-node-end.gif",
"nodeOpen": "tree-node-open.gif",
"nodeOpenEnd": "tree-node-open-end.gif" };
...
this.init = function() {
var p, img;
for (p in this.img) {
this.img[p] = this.path + this.img[p];
}
for (p in this.img) {
this.imgObjects.push(new Image());
this.imgObjects.getLast().src = this.img[p];
this.img[p] = this.imgObjects.getLast().src;
}
this.parse(document.getElementById(this.id).childNodes,
this.tree, 1);
this.loadState();
if (window.addEventListener) {
window.addEventListener("unload", function(e) { self.saveState(); },
false); }
else if (window.attachEvent) { window.attachEvent("onunload",
function(e) { self.saveState(); }); }
this.updateHtml();
};
...
this.nodeClick = function(id) {
var el = document.getElementById(id+"-section");
var node = document.getElementById(id+"-node");
var icon = document.getElementById(id+"-icon");
if (el.style.display == "block") {
el.style.display = "none";
if (this.allNodes[id].isLast()) { node.src =
this.img.nodeEnd; }
else { node.src = this.img.node; }
icon.src = this.img.folder;
this.opened.removeByValue(id);
} else {
el.style.display = "block";
if (this.allNodes[id].isLast()) { node.src =
this.img.nodeOpenEnd; }
else { node.src = this.img.nodeOpen; }
icon.src = this.img.folderOpen;
this.opened.push(id);
}
/* fix ie bug - images not showing */
if (node.outerHTML) { node.outerHTML = node.outerHTML; }
if (icon.outerHTML) { icon.outerHTML = icon.outerHTML; }
};
...
this.updateHtml = function() {
document.getElementById(this.id).innerHTML = this.toHtml();
};

}
Here is my question: we see that this.img is an object, but its
properties are closed in quotes (eg "branch": "tree-branch.gif"). Then
we see in code in function this.init = function() that its properties
are changed via array construction eg:
for (p in this.img) {
this.img[p] = this.path + this.img[p];
}
, but it is not all - when we read the code more we will see that
properties of img object is read via standard way eg:
this.img.nodeEnd;

Furthermore i have seen on other scripts that other author scripters
used this array convention to object/method/property detection
purposes and even for calling a method so it looked like: obj[p](i , j
, o) (where obj was document object and p was "addEventListener"...).
My question is when it is permitted to use this convention and how it
relates to ECMAScript... and most of all how browsers support this
convention and when i can use it ? Especially does i have to put my
properties around double quotes like this:
this.img = {
"branch": "tree-branch.gif",
...
, and can i use this array convention when i create object like this
(whitout double quotes, like presented in your book):
this.img = {
branch: "tree-branch.gif",
...

My last question to this topic is does it have realtion to
ECMAScript[[isPropertyEnumerable]], so when i create object with
properties in quotes it is enumerable in for-in and without double
quote it isnt ?
As my comment for this that it is messy, becouse it is hard to find
does object is an true Array or other object. Another missleading is
that i know when you do:
var a = new Array();
a["src"] = '/my.gif';
and then,
a.src = 'my2.gif';
, then will i have two diffrent value one in a["src"] and one in a.src
(i thin not).
Please help, becouse it is really confusing me.

2. Some things related to js shortcuts:
In constructor like:
function Constr(a , b , c) {
this.a = a || "myVal";
....
}
the notation
this.a = a || "myVal";
is quite natural, becouse it is bitwise OR and when a is not supplied
it is undefined and thus it has no value so this.a will be "myVal".
But i have seen also this:
this._c = this._c | 0;
, where _c was a counter. When _c is first called it is undefined and
the result will be false (this._c will be false). The this _c is used
as a counter like this._c ++; does it make sense ? Should it be like:
this._c = this._c || 0;
, to make values correct ?

3. When i create variable like:
var _c;
, does it have value of null ?

Thanks in advance for answer, waiting for quick reply
Lukasz(Luke) Matuszewski
"

I really would like to ready about this things, espacially to here
about the safest ways to doing OOP in JavaScript...
 
R

Richard Cornford

Luke said:
Here is my emails to Danny Goodman ...
LOL

First email(simple): Subject: JavaScript Arrays
"
We all know the array can act like HashMap,

We all know that a native ECMAScript object can have arbitrarily named
properties added at runtime, and we know that an Array is a modified
native ECMAScript object and so has the characteristics of all native
ECMAScript objects including the ability to have arbitrarily named
properties added at runtime.

It is extremely questionable whether a standard ECMAScript Array can act
like a HashMap, as it is never strictly empty. And in so far as an
ECMAScript Array could be used as a HashMap the non-array plain Object
would be better suited to the task as it is more 'empty' to start with
than an array is.

HashMap functionality is more safely achieved with the creation of a
custom object. This assumes that the HashMap needs to be able to safely
handle any key name, rather than a known set of key names (a set that
can be known to be safe).
but is there a shortcut
for creating such array ? eg
//simple array indexed via numbers
var a = new Array("a", "fdsf", "sada");
or,
a["a", "fdsf", "sada"];
, bo how a to make it an HashMap ? maybe that:
a["key1":"a", "key2":"fdsf", "key3":"sada"]

As last we all know that it works for objects:
a = { "key1":"a", "key2":"fdsf", "key3":"sada"};

That doesn't make sense. It is object-ness that appear to be wanted,
rather than Array-ness, so an Object literal seems the appropriate
creation method, and an Object a preferable object to be using.
Second email: Subject: JavaScript advanced elements
"
Hi !
I am a student from Tech. Univ. Of Gdansk and I am sort
of advanced begginer :) in JavaScript and ECMAScript standards.

So you have read ECMA 262?

1. Moder-browsers quick object construction like this:

function DynamicTree(id) {
...
this.img = {
"branch": "tree-branch.gif",
"doc": "tree-doc.gif",
"folder": "tree-folder.gif",
"folderOpen": "tree-folder-open.gif",
"leaf": "tree-leaf.gif",
"leafEnd": "tree-leaf-end.gif",
"node": "tree-node.gif",
"nodeEnd": "tree-node-end.gif",
"nodeOpen": "tree-node-open.gif",
"nodeOpenEnd": "tree-node-open-end.gif" };

This object has no instance-related values so it would be better defined
on the - DynamicTree - prototype.
...
this.init = function() {
var p, img; ....
};

This method is not using the fact that it is an inner function, so it
would be better defined as a property of the - DynamicTree - prototype.
...
this.nodeClick = function(id) { ...
};
...
this.updateHtml = function() {
document.getElementById(this.id).innerHTML = this.toHtml();
};

And the same applies to these two.
}
Here is my question: we see that this.img is an object,
but its properties are closed in quotes (eg "branch":
"tree-branch.gif").

The property names in Object literals must be quoted if they do not
conform with the ECMA production rules for an Identifier or a numeric
literal (though using numeric literals is not a good idea because of
bugs in Mac IE). Property names that do conform to the production rules
for Identifier may be quoted anyway. The nature of the property value
may influence its type. A quoted value will be a string literal, and so
a value of string primitive type.
Then we see in code in function this.init = function()
that its properties are changed via array construction eg:
for (p in this.img) {
this.img[p] = this.path + this.img[p];
}

There is no "array construction" here. You appear to be thinking that
the bracket notation property accessor is an Array accessing syntax
(like the Java array accessing syntax it resembles). It is not,
ECMAScript has no special Array accessing syntax: see ECMA 262, 3rd
edition; Section 11.2.1.
, but it is not all - when we read the code more we will
see that properties of img object is read via standard
way eg: this.img.nodeEnd;

A dot notation property accessor.
Furthermore i have seen on other scripts that other author
scripters used this array convention to object/method/property
detection purposes and even for calling a method so it looked
like: obj[p](i , j , o) (where obj was document object and p
was "addEventListener"...).

My question is when it is permitted to use this convention

In all circumstances where a dot notation property accessor may be used
an equivalent bracket notation property accessor can be used in its
place.

Dot notation property accessors require that the token following the dot
conform with the ECMAScript production rules for an Identifier. Bracket
notation places no restrictions on the character sequence that may be
used as a property names.
and how it relates to ECMAScript...

ECMA 262, 3rd edition; Section 11.2.1.
and most of all how browsers support this
convention and when i can use it ?

Bracket notation property accessors are a standard language feature
adopted from pre-existing javascript versions.
Especially does i have to put my
properties around double quotes like this:
this.img = {
"branch": "tree-branch.gif",

If "branch" did not conform with the rules for Identifier (which it
does) then it would need to be quoted.
...
, and can i use this array convention when i create object like this
(whitout double quotes, like presented in your book):
this.img = {
branch: "tree-branch.gif",


If "branch" conforms with the rules for Identifier (which it does) then
it need not be quoted.
My last question to this topic is does it have realtion
to ECMAScript[[isPropertyEnumerable]], so when i create
object with properties in quotes it is enumerable in
for-in and without double quote it isnt ?

It makes no difference, the property should be enumerable.
As my comment for this that it is messy, becouse it is
hard to find does object is an true Array or other object.

An array is a specialised object, and property accessors are about
accessing the properties of object. Bracket notation property accessors
are used when accessing numerically indexes properties of an Array
because the string representation of an integer does not conform to the
production rules for an Identifier.
Another missleading is
that i know when you do:
var a = new Array();
a["src"] = '/my.gif';
and then,
a.src = 'my2.gif';, then will i have two diffrent
value one in a["src"] and one in a.src
(i thin not).

That is too garbled to convey meaning.
Please help, becouse it is really confusing me.

2. Some things related to js shortcuts:
In constructor like:
function Constr(a , b , c) {
this.a = a || "myVal";
...
}
the notation
this.a = a || "myVal";
is quite natural, becouse it is bitwise OR

It is _logical_ OR, bitwise is a very different creature.
and when a is not supplied it is undefined and thus
it has no value so this.a will be "myVal".
But i have seen also this:
this._c = this._c | 0;

That is bitwise OR.
, where _c was a counter. When _c is first called it is
undefined and the result will be false (this._c will be false).

No, all bitwise operations have numeric results.
The this _c is used as a counter like this._c ++; does
it make sense ?

Broadly. If the original this._c may be undefined then the bitwise
operation grantees that it is numeric and not NaN. It would be more
normal to explicitly initialise the value of a coutner.
Should it be like:
this._c = this._c || 0;
, to make values correct ?

No, in most contexts it would make no difference, but if this._c may be
a string value that did not represent a number, or an object or function
reference then subsequent post increment operations would result in NaN.
3. When i create variable like:
var _c;
, does it have value of null ?

The value of a local variable is initialised to the Undefined value: see
ECMA 262, 3rd edition; Section 10.1.3.

I really would like to ready about this things,
espacially to here about the safest ways to doing OOP in
JavaScript...

Read the group-'s FAQ:-

<URL: http://www.jibbering.com/faq >

- then ask questions here (and please, if you have any javascript books
by Danny Goodman burn them now).

Richard.
 
R

RobG

Richard said:
Luke wrote:
[...]
As my comment for this that it is messy, becouse it is
hard to find does object is an true Array or other object.


An array is a specialised object, and property accessors are about
accessing the properties of object. Bracket notation property accessors
are used when accessing numerically indexes properties of an Array
because the string representation of an integer does not conform to the
production rules for an Identifier.


If the question here is how to determine if an object is an Array, the
following may help:


var a = [1, 2, 3];

if (('object' == typeof a) && (Array == a.constructor)) {
// a is an array object
}


[...]
 
L

Luke

Richard Cornford napisal(a):
Array could be used as a HashMap the non-array plain Object
would be better suited to the task as it is more 'empty' to start with
than an array is.

True... (there are also things related with prototype properties, so
plain Object is more 'empty'...)
HashMap functionality is more safely achieved with the creation of a
custom object. This assumes that the HashMap needs to be able to safely
handle any key name, rather than a known set of key names (a set that
can be known to be safe).
but is there a shortcut
for creating such array ? eg
//simple array indexed via numbers
var a = new Array("a", "fdsf", "sada");
or,
a["a", "fdsf", "sada"];
, bo how a to make it an HashMap ? maybe that:
a["key1":"a", "key2":"fdsf", "key3":"sada"]

As last we all know that it works for objects:
a = { "key1":"a", "key2":"fdsf", "key3":"sada"};

That doesn't make sense. It is object-ness that appear to be wanted,
rather than Array-ness, so an Object literal seems the appropriate
creation method, and an Object a preferable object to be using.

Well it clears many things to me now.
So you have read ECMA 262?

I have only used parts of it, and i haven't read about [ ] (brackets)
notation of getting object properties, methods etc.
I am working on javadoc version of web browsers objects and methods, to
help me with my everyday work(so i created java version of javadocs
that corresponds to javascript, eg. in ecma262 package i have created
built-in objects ECMA specifies with its methods and related things, in
jsabo(javascript and browser objects) i have started documenting
objects/methods supported in variuos browsers). I have nearly ended
documenting ecma262 (and saw the E4X specs, so added the ecma357
package).
I am using the danny goodman book to document this methdos...
documenting it is really 'fast' if you are using eclipse and you add
some your own templates. And of course i don't do it for nothing or my
pleasure :)...
Maybe i will put it in my website to make it open but first i must end
some importand fragments of it.

PS this DynamicTree script is not my, but i was desperated to copy it
here. Sorry for 'spam', but Danny Goodman book treats on oop very
little.
There is no "array construction" here. You appear to be thinking that
the bracket notation property accessor is an Array accessing syntax
(like the Java array accessing syntax it resembles). It is not,
ECMAScript has no special Array accessing syntax: see ECMA 262, 3rd
edition; Section 11.2.1.
yeap i was looking on javascript like on java language, my mistake :(

Thanks i will read all faqs on http://www.jibbering.com/faq/ before
asking question here...
In all circumstances where a dot notation property accessor may be used
an equivalent bracket notation property accessor can be used in its
place.
Yes it is stated in Section 11.2.1.
Bracket notation property accessors are a standard language feature
adopted from pre-existing javascript versions.
Yeap, here i see that EL language in JSP 2.0 or JSTL 1.0 also uses that
notation. That really clears my thoughts :)
My last question to this topic is does it have realtion
to ECMAScript[[isPropertyEnumerable]], so when i create
object with properties in quotes it is enumerable in
for-in and without double quote it isnt ?

It makes no difference, the property should be enumerable.

Another thing cleared.
An array is a specialised object, and property accessors are about
accessing the properties of object. Bracket notation property accessors
are used when accessing numerically indexes properties of an Array
because the string representation of an integer does not conform to the
production rules for an Identifier.

15.4 of ECMAScpritp 3rd ed. states that:
"Array objects give special treatment to a certain class of property
names. A property name P (in the form of
a string value) is an array index if and only if ToString(ToUint32(P))
is equal to P and ToUint32(P) is not
equal to 232-1.", so only for arrays it is permitted to use the
integer values in brackets as it is an array index.
Another missleading is
that i know when you do:
var a = new Array();
a["src"] = '/my.gif';
and then,
a.src = 'my2.gif';, then will i have two diffrent
value one in a["src"] and one in a.src
(i thin not).

That is too garbled to convey meaning.

, so afeter your explanations i think that a.src and a["src"] has the
same value...(becouse a["src"] means the same as a.src)...
differences come when you use a[0] and a.0 (which i think is not a
valid Identifier).
It is _logical_ OR, bitwise is a very different creature.

sorry, it is my mistake...
&
|
ant other are bitwise...
and
&&
||
are logical :( (probably i was tired when i was writting this, and i
have only remebered that i have to write about bitwise and logical...
but i not read it twice)
That is bitwise OR.


No, all bitwise operations have numeric results.

Yes i know....no comment for my mistake :(
Broadly. If the original this._c may be undefined then the bitwise
operation grantees that it is numeric and not NaN. It would be more
normal to explicitly initialise the value of a coutner.


No, in most contexts it would make no difference, but if this._c may be
a string value that did not represent a number, or an object or function
reference then subsequent post increment operations would result in NaN.
That is another thing that i didn't knew.
Read the group-'s FAQ:-

<URL: http://www.jibbering.com/faq >

- then ask questions here (and please, if you have any javascript books
by Danny Goodman burn them now).

This post looks like spam most of becouse of my bugs (logical/bitwise
ops. like ||,&&/&,|)...

Thanks for this quick answer...but i will not throw away the dannys
book beacouse it has docs for methods supported in different
browsers...
or i will throw it away if you know better source of such
cross-reference of methods/objects in various browsers...
Luke.
 
L

Lasse Reichstein Nielsen

Luke said:
15.4 of ECMAScpritp 3rd ed. states that: ....
so only for arrays it is permitted to use the integer values in
brackets as it is an array index.

No, it's allowed for all objects. Only for arrays it means something
special - that the property is an array element, and assigning to it
might change the length property of the array.

Using the square-bracket notation, any value can be used to get the
property name. If the value is not a string, it is first converted
to a string. Number values convert to string representations of
themselves in the form expected by the array [[Put]] operation, so
they work as array element indices as well.

Example:
---
var o = {};
o[42] = true;
o[null] = true;
o[undefined] = true;
o[false] = true;
var arr = [1,2,3];
o[arr] = true;

alert([o["42"], o["null"], o["undefined"], o["false"], o["l,2,3"]]);
---
....
differences come when you use a[0] and a.0 (which i think is not a
valid Identifier).

Correct. Dot-notation can only be used if the property name is also
a javascript identifier (i.e., starts with [A-Za-z$_] and continues
with [A-Za-z0-9_$]).

/L
 
R

Richard Cornford

Luke said:
Richard Cornford napisal(a):
Thanks for this quick answer...but i will not throw away
the dannys book

I said burn it not throw it away. If you throw it away it may come into
someone else's possession and curse them in turn.
beacouse it has docs for methods supported in different
browsers...
or i will throw it away if you know better source of such
cross-reference of methods/objects in various browsers...

My research has identified approximately 6000 distinct property names
belonging to host objects in web browsers, about 2000 refer to objects.
You will not find a single reference to all of these, indeed a fair
proportion do not appear to be (publicly) documented.

Richard.
 

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,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top