Confused

M

Marvin

Hi:

I have been programming with OOP and C++ for over 10 years but I am new
to javascript. I am very confused about one aspect and would appreciate
it if someone could explain the differences between the following 2
groups of "statements":

function myFunc (x)
{
a = 1;
var a = 1;
a: 1;
this.a = 1;

b = x;
var b = x;
b: x;
this.b = x;

}


TIA
Marvin
 
M

Marvin

Vic Sowers wrote:
Depends on how myFunc is called. If it is called like myVal = myFunc(arg),
this.a refers to the var a in the scope enclosing myFunc, usually the global
scope. So, this.a would refer to the global var 'a'. If myFunc is called
like MyObj = new myFunc(arg), this.a will refer to a property of myFunc and
can be referenced as myObj.a.
Huh?????
In any functions which are a property of
myFunc's prototype property, it can be referenced as this.a.
<snip>

Sorry, I should have phrased my question as follows.....
What is the difference between the following:

myFunc(x) { a = 1; }
myFunc(x) { var a = 1; }
myFunc(x) { this.a = 1; }
myFunc(x) { a : 1; }

I understand the last one. In the 1st, I take it that "a" is defined as
a local variable. In the 2nd, "a" is a global variable. But I am still
confused about "this.a". I am especially confused about the differences
between:

x = myFunc(arg);
x = new myFunc(arg);
x = myFunc;

I think that the first just "executes" myFunc and returns a value. What
about the other 2?


Also, is this:

o = {a:1, b:2, c:3};

the same as the following?

o = new Object;
o.a =1;
o.b = 2;
o.c = 3;


TIA
Marvin
 
T

Thomas 'PointedEars' Lahn

Marvin said:
Vic Sowers wrote:


Huh?????

He meant

var myObj = ...

or "referenced as MyObj.a".

BTW, your Question Mark key is borken.
<snip>

Sorry, I should have phrased my question as follows.....
What is the difference between the following:

myFunc(x) { a = 1; }
myFunc(x) { var a = 1; }
myFunc(x) { this.a = 1; }
myFunc(x) { a : 1; }

The difference is different code. The lines have in common that neither
one is syntactically correct, since the `function' keyword is missing.
I understand the last one.

Are you sure?
In the 1st, I take it that "a" is defined as a local variable.

(Let us assume in the following for brevity that each of the above
lines is prefixed with `function '.)

No, it is not. Since in there is no variable `a' declared in that
execution context, you are adding a new property to the next object
in the scope chain, usually the Global Object (but there are known
side effects with host objects, e.g. in IE). This would be similar
to defining a global variable.

The difference between the behavior here and the behavior with the
code in your previous posting is that there was a VariableDeclaration
for `a' within the same execution context. Hence the first statement
did refer to the next object in the scope chain that had such a property,
which was the VariableObject of the current execution context (and
therefore `a' referred to the local variable. Even though the
VariableStatement followed the assignment, it was parsed first;
the initialization, however, happened later, after the unqualified
assignment.)

Variables should always be declared, or they are no variables attached
to an execution context, but properties of any object in the scope chain.
In the 2nd, "a" is a global variable.

No, it is not. Because the `var' keyword (a VariableStatement) was used,
a new property of the Variable Object of the current execution context
was created. Therefore, a local variable was declared. References to
`a' within this execution context refer to that variable, not to the
(global) property that may have been created before (by calling the first
version of myFunc()).
But I am still confused about "this.a". I am especially confused about the
differences between:

x = myFunc(arg);

Provided that `arg' exists (which I will assume from now for brevity), if
myFunc() is called like this, it is called as a method of the Global Object
(unless there is another object in the scope chain before the Global
Object, see above). Therefore, `this' within myFunc() refers to that
object.
x = new myFunc(arg);

If myFunc() is used as a constructor as called in a NewExpression like here,
`this' within myFunc() refers to the object that is constructed. (That
object inherits directly from myFunc.prototype, and is therefore called a
"myFunc object".)
x = myFunc;

This does not call myFunc(), because it is not a CallExpression (the
argument list is missing) or a NewExpression (there is no prefixed `new'
keyword). `x' is assigned the value of myFunc, which is a reference to a
Function object. Therefore, after that line, x() can be [[Call]]ed and
[[Construct]]ed as if myFunc() was [[Call]]ed or [[Construct]]ed. It is
is not copying an object, it is copying the reference to that object.
[...]
Also, is this:

o = {a:1, b:2, c:3};

the same as the following?

o = new Object;
o.a =1;
o.b = 2;
o.c = 3;

It is. An Object literal is both a constructor and an initializer,
so is an Array literal [1, 2, 3], and a RegExp literal /1+2*3/. The
difference with the RegExp literal is that the corresponding RegExp
object is created before execution, and so is only created once, even
if it is used several times in the code.

This is very basic knowledge (no matter the terms used to describe
it). Please search the archives, RTFAQ[1] RTFM, and STFW, before
you post again.


HTH

PointedEars
___________
[1] <URL:http://jibbering.com/faq/>
 
M

Marvin

Thomas said:
This is very basic knowledge (no matter the terms used to describe
it). Please search the archives, RTFAQ[1] RTFM, and STFW, before
you post again.

All I've been doing for the past couple of weeks is searching the
archives. It is very difficult (near impossible) to find any clear
explanations about this. The only clear explanations seem to be with
basic JavaScript 1.0. If you can point me to some well written, clear
description(s) of the latest JavaScript, I'd appreciate it.

Marvin
 
R

Randy Webb

Marvin said the following on 3/22/2006 4:18 PM:
Thomas said:
This is very basic knowledge (no matter the terms used to describe
it). Please search the archives, RTFAQ[1] RTFM, and STFW, before
you post again.

All I've been doing for the past couple of weeks is searching the
archives. It is very difficult (near impossible) to find any clear
explanations about this. The only clear explanations seem to be with
basic JavaScript 1.0. If you can point me to some well written, clear
description(s) of the latest JavaScript, I'd appreciate it.

Ignore Thomas for the most part. His answers fall into two categories:

1) Quote a lot of crap that doesn't pertain to what really happens.
2) Tell you to RTFM, you are dumb, get a clue, generally condescending.

Neither is worth the ink it takes to display text on a monitor.

ECMAScript is where you want to look.

<URL:
http://www.ecma-international.org/publications/standards/Ecma-262.htm >

Would be the best starting place. Then, test it. Test until you are
tired of testing. The specs are a good place to start to find out how it
should work, then testing will show you how it really works - whether in
accordance to the specs or not - it will show you how it really works.
 
T

Thomas 'PointedEars' Lahn

Marvin said:
Thomas said:
This is very basic knowledge (no matter the terms used to describe
it). Please search the archives, RTFAQ[1] RTFM, and STFW, before
you post again.

All I've been doing for the past couple of weeks is searching the
archives. It is very difficult (near impossible) to find any clear
explanations about this.

Have I not just posted a very clear and detailed explanation of this?
If you do not think so, what parts of it are still unclear?

However, you should try any of the terms "activation object" and
"execution context" as keyword.
The only clear explanations seem to be with basic JavaScript 1.0.
If you can point me to some well written, clear description(s) of
the latest JavaScript, I'd appreciate it.

You could read the FAQ for a start. It also contains links to reference
material as the Wikipedia article on JavaScript does. You will also find
a lot of useful links in my previous articles.

That said, you should get informed about ECMAScript and JScript, too,
because JavaScript 1.1+ and JScript are ECMAScript implementations.


HTH

PointedEars
 
M

Michael Winter


The first sentence above - that the value of the this operator changes -
is correct. The rest is not quite so accurate.

In the course of replying to other posts, I've written about this topic.
Perhaps you'll find one of those posts helpful. The OP replied to one[1]
to say that he found it useful, so hopefully you will, too. If not,
there are others[2] you might try.

If you have any questions about those posts (see the end of this post
for links to the archives), don't hesitate to ask.

[snip]
What is the difference between the following:

Be aware that you omitted the function keyword in the following examples.
myFunc(x) { a = 1; }

The interpreter will search the scope chain for the identifier, a. As it
won't find one as a local variable, or as a declared global variable, a
new property will be created on the global object. This new global
variable will then be assigned the number, 1.
myFunc(x) { var a = 1; }

When this function is called, the interpreter will first create two
local variables. The first is the formal argument, x, and the second is
the declared local variable, a. Before execution of the function begins,
x will be assigned the value passed when the function is called (or
undefined if there was no argument), whilst a will remain undefined.
When execution begins, the variable, a, will be assigned the number, 1,
when that statement is reached.

It's important to note that variable declarations (as well as inner
function declarations) are processed before execution of the function
occurs.

Perhaps the following will be more clear:

function myFunc(x) {
/* Some code */

var a = 1;

/* Some more code */
}

is equivalent to:

function myFunc(x) {
var a; // Note: no initialiser

/* Some code */

a = 1;

/* Some more code */
}
myFunc(x) { this.a = 1; }

A property, a, is created (if necessary) on whatever object the this
operator references, and is assigned the number, 1.
myFunc(x) { a : 1; }

The body of this function contains a label, named 'a', and an expression
statement, 1. There are no variables involved and no assignments, though
the formal argument, x, does exist. Evaluation of the numeric literal,
1, does nothing.

[snip]
I am especially confused about the differences between:

If you've read the posts that I referred you to, you may already
understand the following.
x = myFunc(arg);

The function, myFunc, is called with an argument, arg. The return value
from this function, which may be the value, undefined, is assigned to
the variable, x.
x = new myFunc(arg);

I explained that in some detail in [1].
x = myFunc;

A reference to the function object, myFunc, is assigned to the variable,
x. The following calls are now equivalent:

myFunc();
x();

That is, both result in the execution of the same function object.

[snip]
Also, is this:

o = {a:1, b:2, c:3};

the same as the following?

o = new Object;
o.a =1;
o.b = 2;
o.c = 3;

Yes.

Hope that helps,
Mike


[1] Subject: Re: How do I properly pass a parameter to a
parameterized event handler in a loop?
Date: Sun, 01 Jan 2006 21:07:09 GMT
Message-ID: [email protected]

<http://groups.google.co.uk/group/co...051f3e80a8c/ec26cd885e01c292#ec26cd885e01c292>


[2] Subject: Re: Object oriented stuff and browsers related
thing
Date: Sun, 20 Nov 2005 00:05:09 GMT
Message-ID: [email protected]

<http://groups.google.co.uk/group/co...cb64c504859/1edf3029a9bed649#1edf3029a9bed649>


Subject: Re: How to understand the javascript class model?
Date: Thu, 25 Aug 2005 10:17:30 GMT
Message-ID: [email protected]

<http://groups.google.co.uk/group/co...b9103b6de0f/b33f710ad371e67a#b33f710ad371e67a>
 
R

RobG

Michael Winter said on 23/03/2006 9:51 AM AEST:


The first sentence above - that the value of the this operator changes -
is correct. The rest is not quite so accurate.

In the course of replying to other posts, I've written about this topic.
Perhaps you'll find one of those posts helpful. The OP replied to one[1]
to say that he found it useful, so hopefully you will, too. If not,
there are others[2] you might try.

If you have any questions about those posts (see the end of this post
for links to the archives), don't hesitate to ask.

[snip]
What is the difference between the following:


Be aware that you omitted the function keyword in the following examples.
myFunc(x) { a = 1; }


The interpreter will search the scope chain for the identifier, a. As it
won't find one as a local variable, or as a declared global variable, a
new property will be created on the global object. This new global
variable will then be assigned the number, 1.

Mike I love your stuff, but there's one detail I'd like to add here:
because 'z' is not declared with 'var' anywhere and is initialised
inside a function, it will not be added as a property of the global
object *until the function is executed*.

e.g.

function setZ() { z = 10; }

alert(z); // Error - 'z is not defined', no more code is
// executed in this script element


If the above is 'fixed' so that it runs, the following happens:

function setZ() { z = 10; }

setZ(); // Now z is added as a global property and
// given a value of 10

alert(z); // shows 10


Until the function runs, z is a kind of quasi-global object. The real
fix is to declare z upfront as a global variable:

var z; // z is added as a global variable with value 'undefined'
function ...


The OP should read about the different ways that global code and
function code are handled.

[...]

You answered 'yes' here, I thought there was a typo. It seems that:

1. var x = new Object();

2. var x = Object();

3. var x = new Object;


all assign an object to x. The first is typical, Object is called as a
constructor with the new operator (15.2.2).

The second seems to be based on section 15.2.1.1 - calling the Object
function with no arguments returns a new object as if new Object() had
been called.

The third surprised me, but seems to be based on section 11.2.2 where
the internal [[construct]] method of Object will be called (15.2.4.1
notes Object.prototype.constructor as the built-in Object constructor).
So again, the same as if new Object() had been called.

Is that correct? Are they all equivalent? If so, why are there three
different ways to do the same thing?


Incidentally, I find discussions like this extremely helpful. Trying to
understand how JavaScript works from first principles solely using the
spec may be OK for some but it's a definite challenge for me.

I recently did a search of the archive using 'activation object' and
'execution context' (coincidence that Thomas just suggested it too!) and
came up with some great stuff.
 
V

VK

RobG said:
Mike I love your stuff, but there's one detail I'd like to add here:
because 'z' is not declared with 'var' anywhere and is initialised
inside a function, it will not be added as a property of the global
object *until the function is executed*.

Rob I love your stuff, but there's one detail I'd like to add here ;-)

If the page contains an element like <div id="z">stuff</div> then on
IE:

function f() {
z = 'foobar';
}

will lead to "object doesn't support this method" runtime error. IE
adds references to all id'ed elements to the special scope between
Global and Host; so in the above case it will tread the statement as
DOMDivElement = 'foobar'; which is indeed not supported. If one plans
to destribute her code, it is always necessary to predeclare all clobal
variable in the head section:

var z;
....
function f() {
z = 'foobar';
}

If global variable predeclared it will prevent auto reference to id'ed
element with the same name to be created.

If predeclaring globals is not possible for some reasons (say some
libraries are loaded programmatically after page load) it is always a
good idea to make a check before declaring new global within your
function:

function f() {
if ('undefined' == z) {
z = 'foobar';
}
else {
// the name is already "taken" by id'ed element
}
}
 
T

Thomas 'PointedEars' Lahn

Marvin said:
Thanks. That document looks good. I noticed that it is dated Dec. 1999.
Is that the latest version of JavaScript that is generally used?

You are confusing ECMAScript (ECMA-262) and JavaScript (a common
misconception). (Netscape, now Mozilla.org) JavaScript is an
implementation of the ECMAScript standard. That includes extensions
that are not specified, but sanctioned by the standard (see the
"Conformance" section, and the subsections, especially about the
Global Object). JavaScript is used by Netscape browsers since
version 2.0, and Gecko-based UAs.

JScript is and has been Microsoft's ECMAScript implementation (created
due to competition during the Browser Wars), used by Internet Explorer,
the Windows Script Host, and ASP(.NET).

Other implementations include the Opera implementation (stable since
version 6.0, AFAIK), KJS (the implementation in KHTML, used by Konqueror,
Safari and derivatives), and even ActionScript as used by Macromedia Flash.

The latest revision of ECMAScript Edition 3 is ECMAScript Edition 3 Final,
issued March 2000, which can be obtained from

<URL:http://www.mozilla.org/js/language/>

(The first sentence there, "ECMAScript is the name used for JavaScript as
standardized by the TC39 committee of the ECMA standards organization."
is simplifying the matter, because ECMAScript is based on both JavaScript
and JScript, as you can read at the beginning of each ECMAScript edition.)

JavaScript 1.5 and 1.6 are implementations of ECMAScript Edition 3 Final.
JavaScript 1.6 also implements ECMAScript for XML (E4X), ECMA-357.

See also <URL:http://pointedears.de/scripts/es-matrix>


PointedEars
 
M

Michael Winter

On 23/03/2006 06:43, RobG wrote:

[snip]
function setZ() { z = 10; }
[snip]

Until the function runs, z is a kind of quasi-global object.

I prefer to think that it just doesn't exist. :)

I concede your point, and apologise to the OP if this particular issue
wasn't clear. I'd also note that global variables should not be created
in this fashion: always explicitly declare them using a var statement
(as you mention, Rob).

[snip]
It seems that:

1. var x = new Object();

2. var x = Object();

3. var x = new Object;

all assign an object to x.

Yes, they do.
The first is typical, [...]

And preferred, in my opinion.
The second seems to be based on section 15.2.1.1 [...]

It is.
The third surprised me, but seems to be based on section 11.2.2 [...]

Specifically, the NewExpression production:

NewExpression :
MemberExpression
new NewExpression

Following the grammar, the MemberExpression production:

MemberExpression :
PrimaryExpression
FunctionExpression
MemberExpression [ Expression ]
MemberExpression . Identifier
new MemberExpression Arguments

leads to the PrimaryExpression production:

PrimaryExpression :
this
Identifier
Literal
ArrayLiteral
ObjectLiteral
( Expression )

This permits the use of the new operator with just the name of a
reference (Identifier) to a function object without the need for Arguments.

[snip]
Is that correct? Are they all equivalent?

Yes, or at least they are specified as producing equivalent results. I
don't know how well the Object constructor behaves between browsers when
called as a function, though superficially it seems fine.
If so, why are there three different ways to do the same thing?

The third case is presumably just a convenience for instantiating a new
object without the use of arguments. However, I think it looks messy.
Don't ask me why...

The second case has greater potential. The Object constructor acts as a
wrapper for the internal ToObject operator (9.9, ECMA-262) when called
as a function. The ToObject operator converts its operand to an object,
with objects returned unaltered. However, a null or undefined operand
would throw a TypeError exception, so the Object 'function' returns a
new Object object instead.
Incidentally, I find discussions like this extremely helpful. Trying
to understand how JavaScript works from first principles solely using
the spec may be OK for some but it's a definite challenge for me.

I think I would have great admiration for anyone that did that. ECMA-262
is not easy to read, and it baffled me for the longest time.

Of course, when you do finally understand something properly - or
perhaps I should say, at least when you /think/ so - it always seems so
obvious and you can't imagine what all the fuss was about.
I recently did a search of the archive using 'activation object' and
'execution context' (coincidence that Thomas just suggested it too!)
and came up with some great stuff.

I would have thought that every behavioural aspect as been discussed at
length by now at some point in the group's history. It's just a matter
of finding those discussions. Still, it never hurts to keep having them.
I know that misunderstandings on my part have been corrected when I've
written about technical aspects of the language, and past explanations
can always be improved or presented in a different way[1].

Mike


[1] That isn't a reference to your post, Thomas. I hadn't read
the thread in full, and didn't notice your explanation.
 

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,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top