473,803 Members | 3,416 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 (handleDeleteBu ttonClicked
function) that "this" would be pointing at a ViewController object.
Instead it was the Button (HtmlInputEleme nt).

Can somebody help me understand?

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

/* delete button handler */
ViewController. prototype.handl eDeleteButtonCl icked = function() {
window.alert("d elete clicked, this=" + this + " this.foo= " +
this.foo);
};

/* initializer */
ViewController. prototype.initi alize = function() {
document.getEle mentById("delet e-button").onclic k =
this.handleDele teButtonClicked ;
};
</script>
</head>
<body onload="javascr ipt:new ViewController( ).initialize(); ">
<input id="delete-button" type="button" value="Delete">
</body>
</html>

Oct 20 '06
28 2132
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
FunctionStateme nt vs FunctionExpress ion 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.c om/schools_ring/blogs/Image1.gif>
- shows the stack state for var something = function(){}

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

<http://www.geocities.c om/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.c om/schools_ring/blogs/Image1FF.gif>
shows the stack state for var something = function(){}

<http://www.geocities.c om/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.calle e. Still a bit weird looking but at
least it may have some sense.

Oct 24 '06 #21
In article <11************ *********@b28g2 000cwb.googlegr oups.com>, VK
<sc**********@y ahoo.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 ("transferre d
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.c om/schools_ring/blogs/Image1.gif- shows
the stack state for var something = function(){}

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

<http://www.geocities.c om/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.c om/schools_ring/blogs/Image1FF.gifsho ws the
stack state for var something = function(){}

<http://www.geocities.c om/schools_ring/blogs/Image2FF.gifsho ws 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.calle e. 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.calle e 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************ *********@k70g2 000cwa.googlegr oups.com>, VK
<sc**********@y ahoo.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
5749
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 difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
27
2279
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
4653
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 month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and hash is the base for it. I summarized all points in this article:...
136
9461
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 code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
104
17018
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 that array Could you show me a little example how to do this? Thanks.
11
3324
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 'thoughful' suggestion based on their answers. In terms of the logic involved with the actual script: I've mulled it over and thoroughly broken my brain, trying to devise a complicated 'scoring system' (with different answers giving different...
13
2139
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 parts of the code, but as far as I can see, the way objects work in javascript is quite awkward. I had it working the way they suggest in the book, and it was going OK until I wanted to call one object method from another - I couldn't find a...
6
1913
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 allow the user to type in a value. Also, I would like the 2nd option only editable if the button for that option is selected. All I can seem to find is basic examples of forms, and none of which have this feature. The form would look something...
18
1933
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 requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
0
9703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9565
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10550
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9125
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7604
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6844
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2972
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.