473,499 Members | 1,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OO javascript... this doesn't appear to point to the object

I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller" object
to handle events and interact with the server. However, I apparently
don't fully understand what "this" refers to. In the code below I was
expecting that when the button was clicked (handleDeleteButtonClicked
function) that "this" would be pointing at a ViewController object.
Instead it was the Button (HtmlInputElement).

Can somebody help me understand?

<html>
<head>
<script>
/* Constructor */
function ViewController() {
this.foo = "bar";
}

/* delete button handler */
ViewController.prototype.handleDeleteButtonClicked = function() {
window.alert("delete clicked, this=" + this + " this.foo= " +
this.foo);
};

/* initializer */
ViewController.prototype.initialize = function() {
document.getElementById("delete-button").onclick =
this.handleDeleteButtonClicked;
};
</script>
</head>
<body onload="javascript:new ViewController().initialize();">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

Oct 20 '06 #1
28 2089
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller"
object to handle events and interact with the server. However, I
apparently don't fully understand what "this" refers to.
Then search the Google Groups archives for phrases like "the this
operator" and such. It has been discussed many times in the past.

Be careful to ignore anything a poster named "VK" has to say on the matter.

[snip]

Mike
Oct 20 '06 #2
VK
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller" object
to handle events and interact with the server.
IMHO your code looks more as an attempt to reproduce other languages
weaknesses and workarounds in javascript. The javascript event model
has enough of its own headaches to add Java's or C++'s ones into it ;-)

<html>
<head>
<titlemake KISS - then OOP ! </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<script type="text/javascript">

function EventListener(obj) {

// Lightweight constructor protection:
if (((window) && (this == window))
|| (!obj) || (!obj.tagName)) {
return new Boolean(false);
}

obj.JSInstance = this;

this.foo = 'foo';

for (var i=1; i<arguments.length; i++) {
obj[arguments[i]] = EventListener[arguments[i]];
}
}

EventListener.onmouseover = function() {
this.style.backgroundColor = 'yellow';
}

EventListener.onmouseout = function() {
this.style.backgroundColor = '';
}

EventListener.onclick = function() {
alert(this.JSInstance.foo);
}
function init() {
new EventListener(document.getElementById('btnAdd'),
'onmouseover', 'onmouseout');

new EventListener(document.getElementById('btnEdit'),
'onclick' );

new EventListener(document.getElementById('btnDelete') ,
'onmouseover', 'onmouseout', 'onclick' );
}
window.onload = init;
</script>
</head>

<body>
<button id="btnAdd" type="button">Add</button>
<button id="btnEdit" type="button">Edit</button>
<button id="btnDelete" type="button">Delete</button>

</body>
</html>
However, I apparently
don't fully understand what "this" refers to.
[this] refers to the *current object* (or by ECMAScript specs it points
to "the object pointed by [this] keyword", which is cool to know but
not very helpful :-)

Current object can be:
1) Global object (most of the time)
2) New object instance (in constructor)
3) Object instance owning the called method (more rarely than it should
IMHO)
4) Other object instance transferred by call() or apply() methods
5) Equivalent of *default object* in with (this) {...} construct
6) DOM element received the event in intrinsic method handlers.

By the rules of good show I placed your case at the very end :-)

Oct 21 '06 #3

ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller" object
to handle events and interact with the server. However, I apparently
don't fully understand what "this" refers to. In the code below I was
expecting that when the button was clicked (handleDeleteButtonClicked
function) that "this" would be pointing at a ViewController object.
Instead it was the Button (HtmlInputElement).

Can somebody help me understand?

<html>
<head>
<script>
/* Constructor */
function ViewController() {
this.foo = "bar";
}

/* delete button handler */
ViewController.prototype.handleDeleteButtonClicked = function() {
window.alert("delete clicked, this=" + this + " this.foo= " +
this.foo);
};

/* initializer */
ViewController.prototype.initialize = function() {
document.getElementById("delete-button").onclick =
this.handleDeleteButtonClicked;
};
</script>
</head>
<body onload="javascript:new ViewController().initialize();">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

More research got me to an answer: "this" does not always refer to the
object for which you work. Specifically when called by an event
handler the called function will have "this" set to the control for
whom the event was generated (e.g., button). The original objective
(having a controller object) can be resolved by one level of
indirection:

<html>
<head>
<script>
function initialize() {
var controller = new ViewController();
document.getElementById("delete-button").onclick = function() {
controller.handleDeleteButtonClicked();
}
}

/* constructor */
function ViewController() {
this.foo = "bar";
}

/* delete button handler */
ViewController.prototype.handleDeleteButtonClicked = function() {
window.alert("delete clicked, this' constructor=" +
this.constructor);
};

</script>
</head>
<body onload="javascript:initialize();">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

Oct 21 '06 #4

VK wrote:
ensemble wrote:
I'm trying to utilized a more object-oriented approach to managing
window events in javascript. Thus, I am creating a "controller" object
to handle events and interact with the server.

IMHO your code looks more as an attempt to reproduce other languages
weaknesses and workarounds in javascript. The javascript event model
has enough of its own headaches to add Java's or C++'s ones into it ;-)

<html>
<head>
<titlemake KISS - then OOP ! </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<script type="text/javascript">

function EventListener(obj) {

// Lightweight constructor protection:
if (((window) && (this == window))
|| (!obj) || (!obj.tagName)) {
return new Boolean(false);
}

obj.JSInstance = this;

this.foo = 'foo';

for (var i=1; i<arguments.length; i++) {
obj[arguments[i]] = EventListener[arguments[i]];
}
}

EventListener.onmouseover = function() {
this.style.backgroundColor = 'yellow';
}

EventListener.onmouseout = function() {
this.style.backgroundColor = '';
}

EventListener.onclick = function() {
alert(this.JSInstance.foo);
}
function init() {
new EventListener(document.getElementById('btnAdd'),
'onmouseover', 'onmouseout');

new EventListener(document.getElementById('btnEdit'),
'onclick' );

new EventListener(document.getElementById('btnDelete') ,
'onmouseover', 'onmouseout', 'onclick' );
}
window.onload = init;
</script>
</head>

<body>
<button id="btnAdd" type="button">Add</button>
<button id="btnEdit" type="button">Edit</button>
<button id="btnDelete" type="button">Delete</button>

</body>
</html>
However, I apparently
don't fully understand what "this" refers to.

[this] refers to the *current object* (or by ECMAScript specs it points
to "the object pointed by [this] keyword", which is cool to know but
not very helpful :-)

Current object can be:
1) Global object (most of the time)
2) New object instance (in constructor)
3) Object instance owning the called method (more rarely than it should
IMHO)
4) Other object instance transferred by call() or apply() methods
5) Equivalent of *default object* in with (this) {...} construct
6) DOM element received the event in intrinsic method handlers.

By the rules of good show I placed your case at the very end :-)
Hi VK -
I'm curious to more about your comment "IMHO your code looks more as an
attempt to reproduce other languages weaknesses and workarounds in
javascript." I haven't done a lot of javascript progamming. However,
I'm interested in apply object oriented approaches to this environment.
GUIs were originally developed using OO languages and it seems natural
to me to apply the same principals here. I'm sure you are aware of all
of the literature being introduced right now on the topic of OO and
javascript development.

It sounds like you might have taken this path yourself and found it was
more frustrating than beneficial? Would be interested in your views....

Oct 21 '06 #5
TC

ensemble wrote:
GUIs were originally developed using OO languages

Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!

TC (MVP MSAccess)
http://tc2.atspace.com

Oct 21 '06 #6
TC

TC wrote:
ensemble wrote:
GUIs were originally developed using OO languages


Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.

TC (MVP MSAccess)
http://tc2.atspace.com

Oct 21 '06 #7
ensemble wrote:

[snip]
I'm curious to more about your comment "IMHO your code looks more as
an attempt to reproduce other languages weaknesses and workarounds in
javascript."
There is a growing movement to make ECMAScript and its implementations
look like other languages - Python, for example. One problem is that
these wrappers invite the assumption that because the two languages now
look like one another, they act in the same way, too. This reasoning is
flawed and unproductive: understanding the real, underlying language is
the only way to really appreciate behaviour.
I haven't done a lot of javascript progamming. However, I'm
interested in apply object oriented approaches to this environment.
Do keep in mind the practicality of OO and ECMAScript. There is
sometimes little point in developing an OO solution to a problem, and
doing so only adds bloat. If there is a real return on investment from
taking an OO path, then by all means do so, but think if the benefits
are marginal.

[snip]

Mike
Oct 21 '06 #8
TC wrote:
TC wrote:
>ensemble wrote:
>>GUIs were originally developed using OO languages

Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!

Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.
They had light pens that were functionally equivalent to mice, and used
drag and drop in graphics applications (drag the chair from the
furniture library to the conference room, drag the resistor from the
component library and insert it in the circuit, etc., etc.). They were
much too expensive to use as word processors, etc..

--
John W. Kennedy
"The blind rulers of Logres
Nourished the land on a fallacy of rational virtue."
-- Charles Williams. "Taliessin through Logres: Prelude"
Oct 22 '06 #9
TC wrote:
ensemble wrote:
GUIs were originally developed using OO languages


Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Without a clear definition of what constitutes a GUI and an OO
language, that's not much more than idle boast. While the definitional
debate in regard to GUIs could rage for ages, there seems to be
agreement that SIMULA I (1962) was the first OO language.

<URL:
http://heim.ifi.uio.no/~kristen/FORS..._OO_start.html >

Probably the first interface that implemented most of the fundamental
principles of a modern GUI was oNLine, creation of which started in
1962, although it wasn't revealed to the world until 1968.

<URL: http://www.kernelthread.com/mac/oshistory/2.html >

Therefore to claim that GUI's predate OO languages seems incorrect,
though I'd like to note that you don't need an OO language to write OO
programs, or to write a GUI.
--
Rob

Oct 22 '06 #10
TC

John W. Kennedy wrote:
TC wrote:
TC wrote:
ensemble wrote:

GUIs were originally developed using OO languages

Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.

They had light pens that were functionally equivalent to mice, and used
drag and drop in graphics applications (drag the chair from the
furniture library to the conference room, drag the resistor from the
component library and insert it in the circuit, etc., etc.). They were
much too expensive to use as word processors, etc..
Indeed, I'd forgotten the light pens! I now remember some cases where
you could point & click by using those pens - sort of like a modern
touchscreen. Well before OO existed :-)

TC (MVP MSAccess)
http://tc2.atspace.com

Oct 22 '06 #11
VK
Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.
IMHO GUI is Graphical User Interface, nothing less but nothing more. It
is not in relevance to OOP. That can be OOP program w/o GUI and GUI
program w/o OOP.
I don't dare to go back to the happy 60's :-) but back in 1982 I was
impressed by ArtStudio program - I don't remember producers - on my ZX
Spectrum (1MHz, 64Kb RAM). This color bitmap picture editor had
drop-down menus, drag/drop features, context-dependant screen pointer
(manipulated by joystick). Of course all of this was written in direct
processor commands (the only language which worth anything :-)) But I
don't think that we should take the ZX Spectrum processor commands set
as a sample of an OOP language :-)

Object Oriented Programming assumes that you program manipulates with
different objects having different properties. And if you don't see any
suitable object around, you take the most convenient object among the
existing ones and you build a new custom object on its basis.

That's it: all the rest is propaganda, so students would not just learn
OOP thinking, but also would "sit on the needle" of a particular
OOP-capable language (because these are IDE's, patches and updates they
will buy later - and future software they will write for the glory of
IDE producers). I don't see any lack of "pushers" in higher schools and
in bookstores.

That is all IMHO without any claims to be "universally true" or to be
true at all (though I believe in the latter).

Oct 22 '06 #12
VK
ensemble wrote:
I'm curious to more about your comment "IMHO your code looks more as an
attempt to reproduce other languages weaknesses and workarounds in
javascript." I haven't done a lot of javascript progamming. However,
I'm interested in apply object oriented approaches to this environment.
GUIs were originally developed using OO languages and it seems natural
to me to apply the same principals here. I'm sure you are aware of all
of the literature being introduced right now on the topic of OO and
javascript development.
It sounds like you might have taken this path yourself and found it was
more frustrating than beneficial?
"I am doing what I like. What I like is OOP. You don't like what I am
doing. You don't like OOP."

As I don't have Dodgson's (Caroll) syllogistic talents, I better stay
on plain words :-)

As my grand dad used to say: "Do not mix God's gift and an omelet" :-)
Other words let's us do not mix two all different things together i)
OOP paradigm and ii) language specific algorithms to accomplish this
paradigm. A good amount of "Really Truly Proper JavaScript OOP"-like
books have one default which renders them into rather confusing
sources. Namely a lot of them are written with the statement "the
OOP-ready language I already know == OOP" taken for true; as the result
the whole subject gets seamlessly substituted from "OOP in JavaScript"
to "Emulation of *** language in JavaScript".
>From the positions of OOP itself one could spell your task as: "I need
new class of buttons extending the default DOM button. Each instance
has to have ..., ... properties and react on ..., ... events in the
following way:... I want to be able to create new classes of buttons
based on my class: with even more properties but also with all
properties inherited from the underlying classes".

That is all what OOP has to say on the subject.
Any "controllers", "listeners", "dispatcher", "do this, not that" is
not OOP: these are specific tools to implement OOP paradigm in a
specific language environment. In the particular the idea of controller
is most probably coming from C++ (second best guess - Java). In these
languages objects "do not hear, do not see" any events until one teach
them to do so over added interfaces. And with thousands of objects each
firing dozens of types of custom events with a rate up to single system
tick you need an event queue and some dispatcher so things wouldn't go
to hell completely.
JavaScript doesn't need any of this. Sure you can implement controllers
and even centralized dispatcher by language tools, but it would be
higher level duplicate implementation atop of existing lower level
implementation (== not needed).

P.S. IMHO
P.P.S. I love OOP :-) and I'm using nothing but OOP in high level
languages programming.

Oct 22 '06 #13
In article <11**********************@m73g2000cwd.googlegroups .com>, VK
<sc**********@yahoo.comwrites

<snip>
>3) Object instance owning the called method (more rarely than it should
IMHO)
<snip>

If you do
b.f = a.f;
when f is a function object, is it a or b that now owns the
function?

John
--
John Harris
Oct 22 '06 #14
VK

John G Harris wrote:
If you do
b.f = a.f;
when f is a function object, is it a or b that now owns the
function?
No one: until this function is called. And then it's owned by the
calling object instance (unless "incontinence of [this]" problem say
for timed calls). It is not an exact analogy, but it may help to think
of 100 Java objects having static method f(). Which one of the hundred
"owns" f() ?

I did not mean exactly that in my first post, but it is covered as well
by "reproduce other languages weaknesses and workarounds in
javascript". The question of "b.f = a.f", once so popular in Java
topics is simply not applicable to JavaScript. It doesn't use
(internally) OID stamping for members as say C++ or Java do. That is
why a good OOP style for JavaScript used to be: "if a method will
appertain to a number of instances and if it doesn't need to store
instance-specific info: then make it static". You create function only
once and then reference it in instances. At the most wild times of
Browser Wars it still seemed natural and resource wise to:

function f() {
}

function myConstructor() {
this.method = f;
}

That was this way until C++'er came and started to teach "ignorants"
what the real OOP is about :-) Now if some constructor doesn't have at
least couple of closures (desirable nested ones) and inner functions
then it is not OOP but some crap. And of course no static methods: for
1000 objects we will replicate 1000 anonymous functions. Surely all
this eats memory and leaks like an old barn's roof on IE: but no
sacrificion is big enough for Real OOP :-)

Oct 22 '06 #15
TC wrote:
John W. Kennedy wrote:
>TC wrote:
>>TC wrote:
ensemble wrote:

GUIs were originally developed using OO languages
Uh, say what? GUIs existed before the notion of object oriented
languages had even been thought of!
Hmm, perhaps I should qualify that. Certainly there were graphic
terminals back in the 1960's. These could display (and allow for entry
of) information, somewhat like a modern GUI. But they did not have
mice, or allow for common modern GUI features like drag & drop. So I
guess they were not GUIs in the modern sense of the word.
They had light pens that were functionally equivalent to mice, and used
drag and drop in graphics applications (drag the chair from the
furniture library to the conference room, drag the resistor from the
component library and insert it in the circuit, etc., etc.). They were
much too expensive to use as word processors, etc..

Indeed, I'd forgotten the light pens! I now remember some cases where
you could point & click by using those pens - sort of like a modern
touchscreen. Well before OO existed :-)
The first two generations of 3270 could use light pens for clicking, but
couldn't drag or draw. Light pens generally fell out of use for
ergonomic reasons.

--
John W. Kennedy
"The blind rulers of Logres
Nourished the land on a fallacy of rational virtue."
-- Charles Williams. "Taliessin through Logres: Prelude"
Oct 23 '06 #16
In article <11**********************@m73g2000cwd.googlegroups .com>, VK
<sc**********@yahoo.comwrites
>
John G Harris wrote:
>If you do
b.f = a.f;
when f is a function object, is it a or b that now owns the
function?

No one: until this function is called. And then it's owned by the
calling object instance
Nonsense. When your code does b.f() the code inside f starts with
this === b
this goes back to its previous value when f finishes.

It's as simple as that. Ownership has nothing to do with it.

>(unless "incontinence of [this]" problem say
for timed calls). It is not an exact analogy, but it may help to think
of 100 Java objects having static method f(). Which one of the hundred
"owns" f() ?

I did not mean exactly that in my first post, but it is covered as well
by "reproduce other languages weaknesses and workarounds in
javascript". The question of "b.f = a.f", once so popular in Java
topics is simply not applicable to JavaScript. It doesn't use
(internally) OID stamping for members as say C++ or Java do.
<snip>

You've been reading the wrong web pages. OIDs in C++ - good grief!
John
--
John Harris
Oct 23 '06 #17
VK
If you do
b.f = a.f;
when f is a function object, is it a or b that now owns the
function?
No one: until this function is called. And then it's owned by the
calling object instance
Nonsense. When your code does b.f() the code inside f starts with
this === b
this goes back to its previous value when f finishes.
It's as simple as that. Ownership has nothing to do with it.
"Ownership" is not a programming category at all. I used this term from
your post poetically and I put it into quotes at the end ("transferred
meaning" quotes).

But you are right pointing to an omission:
"No one: until this function is called. And then it's owned by the
calling object instance <ins>during the call</ins>." - that will be
better.
You've been reading the wrong web pages. OIDs in C++ - good grief!
You've been learning from wrong prof's :-)
OID's are the basic for class-based languages - once again - in the
internal mechanics.
But we can stay on the level of the language itself by saying that
JavaScript doesn't implement encapsulation unlike C++ or say Java do.

Oct 23 '06 #18
VK
>If you do
> b.f = a.f;
>when f is a function object, is it a or b that now owns the
>function?
"No one: until this function is called. And then it's owned by the
calling object instance <ins>during the call</ins>." - that will be
better.
I maybe have to explain it better because it is one of important
aspects of JavaScript OOP (completely missed in 99.9% of relevant
books) .

* JavaScript objects do not have "owner / owned" relations as such. *

It is not in any relevance of what inheritance is used: a classy
emulated one or a prototype-based one. JavaScript do not use
encapsulation (doesn't use OID stamping) and internally it is a pure
ideal communism :-) - everyone can take anything it wants but it cannot
take it into exclusive use.
Instead JavaScript uses the backward lookup chain: say if you call
a.f(), the engine finds [a] and if it contains named property [f]
containing in turn a reference to some function, [a] becomes a
"temporary owner" of that function, but only for the period of the
function execution. That can be 1,000 other objects referencing said
function and no one is more "owner" than [a]. That is why "who owns
this function (method)" is pointless in JavaScript. With the same
success one could ask, "what is the temperature of the darkness" or
similar.

If I started on that, I would like to point to another common
misunderstanding, which is IMHO in relation with "who owns who".

I mean the constructs
function name() {}
and
var name = function(){};

First of all, 1) the common mistake is that they are equivalent. 2)
Second - not a mistake, but misconception maybe - is that
MyObject.method = function(){};
or at least
MyObject.prototype.method = function(){};
do establish some special "ownership" relations between MyObject and
the assigned function.

1)
function myFunction() {}
and
var myFunction= function(){};
are not equivalent and their evaluation leads to very different
results. In the first case we are creating named function myFunction
(one object). In the second case we are creating anonymous function
(identified internally by an unique dispid), then we are creating
variable myFunction and then we are assigning a reference of that newly
created anonymous function to the variable myFunction (two different
objects).
>From my previous experience I know that the understanding of this
difference creates difficulties even for most experienced javascript
programmers. (see
<http://groups.google.com/group/comp.lang.javascript/msg/dfb09051f1dfb1c8>)

Maybe some pictures will help this time:

<http://www.geocities.com/schools_ring/blogs/Image1.gif>
- shows the stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2.gif>
- shows the stack state for function something(){}

<http://www.geocities.com/schools_ring/blogs/Image3.gif>
- shows the stack state for var something = function name(){}
(The latter syntax beyond my humble understanding but recently I see it
increasingly in software products clamed to be made by professional
developers. Must be another "discover" in JavaScript made by some
C++'ish writer. So I just added it here so at least readers of this
article would not look silly in their codes.)

2) Now it is easy to see why
MyObject.method = function(){};
doesn't create any special relations between MyObject and function(){};

We are simply adding a reference to anonymous function to the named
property "method". The function itself remains the same "free cat" as
it was before. So *functionally* it is exact equivalent of:
function something(){}
MyObject.method = something;

Oct 24 '06 #19
VK wrote:

[snip]
I mean the constructs
function name() {}
and
var name = function(){};

First of all, 1) the common mistake is that they are equivalent.
Exactly equivalent? No, certainly not. However, in most ways that
matter, they are the same.

[snip]
function myFunction() {}
and
var myFunction= function(){};
are not equivalent and their evaluation leads to very different
results.
Both establish a new property, myFunction, within the variable object of
the "enclosing" execution context. That is to say that both create a
local variable. Both create a function object, and that object has the
same formal arguments, the same scope chain, the same properties,
values, and prototype chain, and the same function body. The only
difference between them is /when/ the function object is created: this
doesn't occur for the latter until the function expression is evaluated
during execution (assuming it even is evaluated).

As I wrote above, the two forms aren't exactly the same, but they are in
most ways that matter.
In the first case we are creating named function myFunction (one
object).
When a function declaration is present within the body of some function
(F), a new local variable is created just before execution of F with the
name given in that declaration (myFunction) and is assigned the function
object that results from evaluating the function declaration. It is a
two-step process.
In the second case we are creating anonymous function (identified
internally by an unique dispid),
How any object is identified internally is of no relevance to anyone (at
least not to anyone who isn't embedding a scripting engine into an
application). Certainly, how Microsoft might do it provides little
insight to any other implementation.
then we are creating variable myFunction and then we are assigning a
reference of that newly created anonymous function to the variable
myFunction (two different objects).
You have that backwards. After all function declarations have been
processed, any variable declarations (var statements) within the body of
a function cause new properties to be added to the variable object each
with the value, undefined. If the initialiser is evaluated during the
course of normal execution, only then will the right-hand side of the
assignment expression be assigned to the variable. It is at this stage
that the function expression is evaluated.

[snip]
<http://www.geocities.com/schools_ring/blogs/Image1.gif>
- shows the stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2.gif>
- shows the stack state for function something(){}

<http://www.geocities.com/schools_ring/blogs/Image3.gif>
- shows the stack state for var something = function name(){}
How is that useful or helpful to anyone? What pertinent information do
you even think it shows? As far as I can see, all it demonstrates is the
choices that Microsoft Script Debugger makes when referring to functions.
(The latter syntax beyond my humble understanding but recently I see
it increasingly in software products clamed to be made by
professional developers. Must be another "discover" in JavaScript
made by some C++'ish writer. So I just added it here so at least
readers of this article would not look silly in their codes.)
Whether they look silly or depends upon how they use the latter.

The identifier in a function expression can only be used within the body
of that function. It is added to the scope chain of the "enclosing"
execution context before creation of the function object, removed
afterwards, and is a reference to the newly created function. It is,
effectively, a local variable, therefore using it outside of the
function body as if the expression was a function declaration is illegal.

[snip]

Mike
Oct 24 '06 #20
VK

Michael Winter wrote:
Exactly equivalent? No, certainly not. However, in most ways that
matter, they are the same.
"ways that matter" is a dangerous term: it may cover too many things in
too ambiguous way (say OOP or not OOP, inheritance emulation or native
inheritance: these issues can be dismissed by this term as well
occasionally).

function f() {}
and
var f = function(){};

have the same internal difference as:
var f = new Function;
and
var a = new Function;
var f = a;

(I am talking about referencing and memory representation, not about
FunctionStatement vs FunctionExpression differences).

Is this matter or not? It depends on circumstances. At the very least
an universal finalizing "it is not matter" is not applicable here.
then we are creating variable myFunction and then we are assigning a
reference of that newly created anonymous function to the variable
myFunction (two different objects).

You have that backwards.
Yep. I wanted to follow-up correction right away, but decided to give
the pleasure of correction to experts. :-)

<http://www.geocities.com/schools_ring/blogs/Image1.gif>
- shows the stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2.gif>
- shows the stack state for function something(){}

<http://www.geocities.com/schools_ring/blogs/Image3.gif>
- shows the stack state for var something = function name(){}

How is that useful or helpful to anyone? What pertinent information do
you even think it shows? As far as I can see, all it demonstrates is the
choices that Microsoft Script Debugger makes when referring to functions.
<http://www.geocities.com/schools_ring/blogs/Image1FF.gif>
shows the stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2FF.gif>
shows the stack state for function something(){}

If you insist, I can use a full-scaled C++ spy so we would count "one
against two" on a big UA-independed picture. But it will most probably
make me all upset and grunchy afterwards (as any person vasted his time
on useless experiment). :-) :-|
< about var f = function f(){} >
Whether they look silly or depends upon how they use the latter.
Thinking back I see some sense in using
var f = function f(){} // both identifiers are the same

That allows to normalize function toString results and to use function
name instead if arguments.callee. Still a bit weird looking but at
least it may have some sense.

Oct 24 '06 #21
In article <11*********************@b28g2000cwb.googlegroups. com>, VK
<sc**********@yahoo.comwrites
>If you do
b.f = a.f;
when f is a function object, is it a or b that now owns the
function?
>No one: until this function is called. And then it's owned by the
calling object instance
>Nonsense. When your code does b.f() the code inside f starts with
this === b
this goes back to its previous value when f finishes.
It's as simple as that. Ownership has nothing to do with it.

"Ownership" is not a programming category at all. I used this term from
your post poetically and I put it into quotes at the end ("transferred
meaning" quotes).
It was *your* article that first talked about owning.

>But you are right pointing to an omission:
"No one: until this function is called. And then it's owned by the
calling object instance <ins>during the call</ins>." - that will be
better.
You've still got it wrong!!!!!!!!!!!

It's not owned, and it's not the "calling object instance".

>You've been reading the wrong web pages. OIDs in C++ - good grief!

You've been learning from wrong prof's :-)
I've got a pdf copy of the C++ ISO Standard. Neither OID nor Object
Identifier appear anywhere in the Standard. They are nothing to do with
the C++ language.

>OID's are the basic for class-based languages - once again - in the
internal mechanics.
I suspect you've been reading about .NET. Perhaps Microsoft have put
things called OIDs into their .NET implementation, but other people
haven't.

>But we can stay on the level of the language itself by saying that
JavaScript doesn't implement encapsulation unlike C++ or say Java do.
Javascript implements encapsulation, but some details are different from
C++ and Java, just as C++ and Java differ in some details.

John
--
John Harris
Oct 24 '06 #22
VK

John G Harris wrote:
It was *your* article that first talked about owning.
"Object instance owning the called method " -
yep, my bad, the same omission
Object instance currently "owning" the called method

the word "currently" and quotes would possibly prevent this branch -
but should we regret about it?
>
But you are right pointing to an omission:
"No one: until this function is called. And then it's owned by the
calling object instance <ins>during the call</ins>." - that will be
better.

You've still got it wrong!!!!!!!!!!!

It's not owned, and it's not the "calling object instance".
that's getting too far from programming into free arts aspects (styles
of speech etc.) Which verb do you want? using? executing? grabbing?
putting hands on? as by ECMAScript lingo it is using "internal [[Call]]
property" then "calling" would be the most appropriate IMHO. Or it is
not an object instance? or object but not an instance (just Object)? or
an instance but not an object (just "stuff")? :-)
I've got a pdf copy of the C++ ISO Standard. Neither OID nor Object
Identifier appear anywhere in the Standard.
Of course they don't. Same way scavengers, garbage collector and memory
heaps do not normally appear in JavaScript specifications. Why do you
think I used the word "internally"? Externally (for the language) it is
called encapsulation. But encapsulation is not a natural phenomenon
falled into C++ by His will :-) It is just another abstraction - and
oid stamping is how this abstraction is internally ticking.
Javascript implements encapsulation, but some details are different from
C++ and Java, just as C++ and Java differ in some details.
Some small sample maybe?

Oct 24 '06 #23
VK wrote:
Michael Winter wrote:
>Exactly equivalent? No, certainly not. However, in most ways that
matter, they are the same.

"ways that matter" is a dangerous term: it may cover too many things
in too ambiguous way ...
Except it doesn't here. I provided (what I believe to be, anyway) a very
clear explanation in my previous post.

[snip]
function f() {}
and
var f = function(){};

have the same internal difference as:
var f = new Function;
and
var a = new Function;
var f = a;
So none, then? In all four cases, there's a function object referenced
by a variable, f. In the latter case, there's an extra reference, a, but
that changes nothing about the function object itself.

The most significant, potential difference between the two pairs is that
function objects created via the Function constructor function may only
ever have the global object in their scope chain.

[snip]
>><http://www.geocities.com/schools_ring/blogs/Image1.gif- shows
the stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2.gif- shows
the stack state for function something(){}

<http://www.geocities.com/schools_ring/blogs/Image3.gif- shows
the stack state for var something = function name(){}

How is that useful or helpful to anyone? What pertinent information
do you even think it shows? As far as I can see, all it
demonstrates is the choices that Microsoft Script Debugger makes
when referring to functions.

<http://www.geocities.com/schools_ring/blogs/Image1FF.gifshows the
stack state for var something = function(){}

<http://www.geocities.com/schools_ring/blogs/Image2FF.gifshows the
stack state for function something(){}
That doesn't answer either of my questions. In fact, it provides even
less information than before.

That Microsoft Script Debugger uses the identifier in a function
declaration to refer to that function means absolutely nothing, except
perhaps the implication that JScript keeps such information around. You
presented it before as a supposed means of education, yet I fail to see
what relevance it has to anything. What is it supposed to teach me or
anyone else? How does it help someone understand how functions behave,
or the behavioural differences between function expressions and
declarations? My suspicion is that it's just an irrelevance.
If you insist, I can use a full-scaled C++ spy so we would count "one
against two" on a big UA-independed picture. ...
Why? That still wouldn't answer my questions.

[snip]
Thinking back I see some sense in using
var f = function f(){} // both identifiers are the same

That allows to normalize function toString results and to use
function name instead if arguments.callee. Still a bit weird looking
but at least it may have some sense.
A better, albeit artificial, example would be:

(function outer() {
function inner() {
/* ... */
}
})();

The arguments.callee property is one means of referencing a function
object created via a function expression within the function itself, but
in the example above, that wouldn't help at all if code within the body
of the inner function needed to reference the enclosing function; there,
the callee property would reference the inner function. The identifier,
outer, can provide that reference. It can also be used instead of the
callee property (where that would be suitable) as a more meaningful way
of accessing the function object for recursion.

Mike
Oct 24 '06 #24
In article <11*********************@k70g2000cwa.googlegroups. com>, VK
<sc**********@yahoo.comwrites
>
John G Harris wrote:
<snip>
>But you are right pointing to an omission:
"No one: until this function is called. And then it's owned by the
calling object instance <ins>during the call</ins>." - that will be
better.

You've still got it wrong!!!!!!!!!!!

It's not owned, and it's not the "calling object instance".

that's getting too far from programming into free arts aspects (styles
of speech etc.) Which verb do you want? using? executing? grabbing?
putting hands on? as by ECMAScript lingo it is using "internal [[Call]]
property" then "calling" would be the most appropriate IMHO. Or it is
not an object instance? or object but not an instance (just Object)? or
an instance but not an object (just "stuff")? :-)
It's code that calls functions. Objects cannot call anything. Therefore
"calling object" has no meaning. You must not use "calling object" in
your personal description of one of the 'this' cases because it would be
meaningless.

Another problem is that there are up to three objects involved in a
function call. You haven't said which object you're talking about.

Incidentally, "object" and "instance" mean the same thing. "object
instance" is redundant, but harmless.

>I've got a pdf copy of the C++ ISO Standard. Neither OID nor Object
Identifier appear anywhere in the Standard.

Of course they don't. Same way scavengers, garbage collector and memory
heaps do not normally appear in JavaScript specifications. Why do you
think I used the word "internally"? Externally (for the language) it is
called encapsulation. But encapsulation is not a natural phenomenon
falled into C++ by His will :-) It is just another abstraction - and
oid stamping is how this abstraction is internally ticking.
<snip>

What do you think an OID is? What do you think OID stamping is?

Whatever they are, the majority of C++ programs don't have them.

John
--
John Harris
Oct 25 '06 #25
VK
The most significant, potential difference between the two pairs is that
function objects created via the Function constructor function may only
ever have the global object in their scope chain.
You probably mean "may only have Global object as current object" (what
[this] points to). That is true except overloaded calls like
FunctionObject.call(context) and FunctionObject.apply(context, args)

A nitpick, I know - but can I do it once? :-)

For the default object the context can be set to anything by say
new Function('arg1', 'arg2', "with(ObjName){...}");
That is really special in function instances created over new
Function() is that body argument is casted to string first and then
re-evaluated on each call. That is the reason you cannot store directly
current [this] value in new Function.
What is it supposed to teach me or
anyone else? How does it help someone understand how functions behave,
or the behavioural differences between function expressions and
declarations? My suspicion is that it's just an irrelevance.
As I said before, I wanted to mention that

function f(){}
obj.method = f;

and

obj.method = function(){}

do not differ anyhow in the "degree of ownership" between obj and its
method.

Oct 26 '06 #26
VK wrote:

Failing to attribute your quotes again?
>The most significant, potential difference between the two
pairs is that function objects created via the Function
constructor function may only ever have the global object
in their scope chain.

You probably mean "may only have Global object as current
object" (what [this] points to).
That is extremely unlikely as Mike knows what he is talking about and so
would not make a false statement, and certainly not using one using such
vague terminology.

As a function created with the Function constructor can be used in the
same way as any other function object, and so assigned to properties of
objects, properties of constructor's prototypes, event handling
attributes and so on, the - this - keyword used within such a function
can refer to all sorts of objects.
That is true except overloaded calls like
FunctionObject.call(context) and
FunctionObject.apply(context, args)
No, what you have just written is just false.
A nitpick, I know - but can I do it once? :-)
You can nit-pick, but you look a fool in the attempt because you don't
know what you are talking about.
For the default object the context can be set to anything
by say new Function('arg1', 'arg2', "with(ObjName){...}");
That will still not put any object other than the global object onto the
function's scope chain, only onto the scope chain of the execution
context used when the function is executed.
That is really special in function instances created over
new Function() is that body argument is casted to string
first and then re-evaluated on each call.
It is hardly unusual for javascript's native functions/constructors to
type-convert their arguments into a required type. It is also not
particularly "special", in the sense of needing any attention being drawn
to, as you would be hard pressed to find any documentation that suggested
using anything but a string as the function body argument.
That is the reason you cannot store
directly current [this] value in new Function.
That does not make sense. What is "store directly current [this] value in
new Function" supposed to mean? In what sense can you "store" any value,
let alone a - this - value, "in" any function (beyond assigning values as
named properties of function objects)?

Are you making a confused stab at referring to specific object instances
through the scope chain of function objects? The ability to do that in a
function object resulting form a function expression/declaration and not
in a function created with the function constructor has nothing to do
with the constructor taking string arguments, it is because " function
objects created via the Function constructor function may only ever have
the global object in their scope chain".
>What is it supposed to teach me or
anyone else? How does it help someone understand how
functions behave, or the behavioural differences between
function expressions and declarations? My suspicion is
that it's just an irrelevance.

As I said before, I wanted to mention that
You never actually answer the questions you are asked, do you. You where
asked to explain what you expected to be learnt from all the URLs you
posted.

That you can never answer these questions makes it very obvious that you
don't know what you are talking about. You may try to hide behind
misdirection to the irrelevant, but you are fooling nobody but yourself.
function f(){}
obj.method = f;

and

obj.method = function(){}

do not differ anyhow in the "degree of ownership" between
obj and its method.
You mean that in a language where there is no "ownership" the degree of
absence of ownership is not influenced by how code is written? A rather
pointless thing to be trying to point out, especially as the only person
likely to imply any notions of "ownership" is you.

Richard.
Oct 27 '06 #27
Richard Cornford wrote:
VK wrote:

Failing to attribute your quotes again?
[MLW:]
>>The most significant, potential difference between the two pairs
is that function objects created via the Function constructor
function may only ever have the global object in their scope
chain.

You probably mean "may only have Global object as current object"
(what [this] points to).

That is extremely unlikely as Mike knows what he is talking about and
so would not make a false statement, and certainly not using one
using such vague terminology.
As much as I appreciate the vote of confidence, I wouldn't put it past
myself. I can only hope that the amount of any lingering ignorance and
the frequency of mistakes on my part would decrease over time.

That said, the particular issue above is hard to get wrong: it's easily
demonstrated, and spelt out quite clearly in step 16, section 15.3.2.1,
ECMA-262 (3rd Ed.)

[snip]

Mike
Oct 27 '06 #28
VK wrote:
>The most significant, potential difference between the two pairs is
that function objects created via the Function constructor function
may only ever have the global object in their scope chain.

You probably mean "may only have Global object as current object"
(what [this] points to). ...
No, I meant what I wrote. The value of the this operator is determined
in same way for function objects no matter how they are created.

[snip]
For the default object the context can be set to anything by say
new Function('arg1', 'arg2', "with(ObjName){...}");
That doesn't change the scope chain of the function object. A with
statement adds the referenced object to the top of the scope chain only
when evaluated and will only affect the code within its own block.
That is really special in function instances created over new
Function() is that body argument is casted to string first and then
re-evaluated on each call.
I'm sorry, what? The arguments to the Function constructor are evaluated
once and the resulting function is constant in its definition. The only
reason to re-evaluate those arguments is if the NewExpression itself is
re-evaluated. That is, if a new function object is created.
That is the reason you cannot store directly current [this] value in
new Function.
What's that supposed to mean?

[snip]

Mike
Oct 27 '06 #29

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

Similar topics

53
5655
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is...
27
2149
by: C Gillespie | last post by:
Dear All, Hopefully I have a simple problem. Basically, I just want to alter some text with JS. Here is some of my test code: <snip> <script type="text/javascript"> var tmp='a';
22
4569
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last...
136
9198
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
104
16845
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
11
3281
by: admin | last post by:
Hi all, First time poster here... I'm a webmaster and I'd like to add a simple script to my website which will allow users to fill in a brief multiple choice questionaire, and then provide a...
13
2072
by: Andy Baxter | last post by:
Can anyone recommend a good online guide to using objects in javascript? The book I bought (DHTML Utopia) suggests using objects to keep the code clean and stop namespace clashes between different...
6
1894
by: drec | last post by:
I am just learning Javascript and I would like to create a basic form that gives me two options. This will be using either checkbox or radio input type, however I would like the second option to...
18
1862
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two...
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
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
7223
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...
1
6899
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
5475
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4602
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...
0
3103
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3094
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
302
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.