473,388 Members | 1,327 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Execute an instance method

Hello.

I have a javascript object with one attribute (name) and one method
(showName). Each object instance appends a DIV to the document's body. I
want that when the user clicks over the DIVS the alert shows the name of
the instance which has created the DIV.tancia que ha creado ese DIV:

See online:
http://www.tel.uva.es/~jpozdom/metodo.html

When the user clicks on the first square the message box should show:
Object1. When the user clicks on the second square the message box
should show: Object2.

I don't know how to do that. The following sentence doesn't work.

this.div.onclick=this.muestraNombre;

Thanks. And excuse my poor english.

<html>
<head>
<script type="text/javascript">
function Objeto(nombre) {
this.nombre=nombre;

this.div=document.createElement('div');
this.div.style.border='1px solid #000';
this.div.style.width='10px';
this.div.style.height='10px';

this.div.onclick=this.muestraNombre;
// Esto no funciona, la función se ejecuta pero
// la referencia this se pierde y aparece 'undefined'

var body=document.getElementsByTagName('body').item(0) ;
body.appendChild(this.div);

}
function MuestraNombre() {
alert(this.nombre);
}
Objeto.prototype.muestraNombre=MuestraNombre;
</script>
</head>
<body>
<script type="text/javascript">obj1=new Objeto('Objeto1');</script>
<p></p>
<script type="text/javascript">obj2=new Objeto('Objeto2');</script>
</body>
</html>
Jul 23 '05 #1
5 1392


Jesús Ángel wrote:

function Objeto(nombre) {
this.nombre=nombre;

this.div=document.createElement('div');
this.div.objeto = this;
this.div.style.border='1px solid #000';
this.div.style.width='10px';
this.div.style.height='10px';

this.div.onclick=this.muestraNombre;
// Esto no funciona, la función se ejecuta pero
// la referencia this se pierde y aparece 'undefined'

var body=document.getElementsByTagName('body').item(0) ;
body.appendChild(this.div);

}
function MuestraNombre() {
alert(this.nombre);


alert(this.objeto.nombre);

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
On Thu, 23 Sep 2004 18:41:22 +0200, Jesús Ángel
<NO**************@computer.org> wrote:

[snip]
The following sentence doesn't work.

this.div.onclick=this.muestraNombre;
[snip]
function MuestraNombre() {
alert(this.nombre);
}

Objeto.prototype.muestraNombre=MuestraNombre;
What's happening is that you assign a function reference, muestraNombre,
as the event listener. The function expects the 'this' operator to point
to an instance of Objeto. This doesn't happen: the operator will actually
refer to the DIV the listener is attached to because it's being called in
the context of that DIV.

If you need to see this in action, replace your MuestraNombre function
with:

function MuestraNombre() {
alert(this);
}

add this after the Objeto definition:

Objeto.prototype.toString = function() {return '[Objeto]';};

this at the end of the script:

var testObject = new Objeto('test');
testObject.muestraNombre();

and run in Mozilla or Opera.

When the page loads, you should see '[Objeto]', signifying that
muestraNombre is using an instance of Objeto through the 'this' operator.
However, when you click on one of your DIVs, you should see '[Object
HTMLDivElement]' [1] (or something similar).

What you've attempted in your original post can be achieved in three ways.
Martin has shown you one. The second has you adding a reference to the
Objeto instance to the new DIV element. The third requires use of a
closure.
this.div=document.createElement('div');
this.div.style.border='1px solid #000';
this.div.style.width='10px';
this.div.style.height='10px';
Why don't you create a CSS rule with a class selector specifying those
property values, and give the new DIV that class name?
var body=document.getElementsByTagName('body').item(0) ;


This can be simplified to:

var body = document.body;

Hope that helps,
Mike
[1] In IE, you'll just see '[Object]', which is why I recommend Opera,
Mozilla, or other good ECMA-262 conforming user agents.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
> What you've attempted in your original post can be achieved in three
ways. Martin has shown you one. The second has you adding a reference
to the Object instance to the new DIV element. The third requires use
of a closure.


Thanks for your answers.

Can you please post a message with an example of the third way (using a
closure).

Two first ways:

<html>
<head>
<style>
..divExample {
width: 10px;
height: 10px;
border: 1px solid #000;
}
</style>
<script type="text/javascript">
function Object(name) {
this.name=name;

this.div=document.createElement('div');
this.div.className='divExample'

// First way
this.div.object=this;
this.div.onclick=function() { this.object.showName() };
/*
// Second way
eval ('this.div.onclick=function() { '+this.name+'.showName() };');
*/

var body=document.body;
body.appendChild(this.div);

}
function showName() {
alert(this.name);
}
Object.prototype.showName=showName;
</script>
</head>
<body>
<script type="text/javascript">Object1=new Object('Object1');</script>
<p></p>
<script type="text/javascript">Object2=new Object('Object2');</script>
</body>
</html>
Jul 23 '05 #4
On Mon, 27 Sep 2004 10:31:58 +0200, Jesús Ángel
<NO**************@computer.org> wrote:

[I wrote this:]
What you've attempted in your original post can be achieved in three
ways. Martin has shown you one. The second has you adding a reference
to the Object instance to the new DIV element.

I got a bit confused here. Martin was actually demonstrating the second
approach, so there are only two useful methods. I thought he was doing
something different.

[snip]
Can you please post a message with an example of the third way (using a
closure).


Certainly.

[snip]

function Objeto(nombre) {
this.nombre = nombre;
this.div = document.createElement('DIV');

// Rest of your code

// This is your MuestraNombre function
this.div.onclick = function() {
alert(nombre);
};
}

The inner function expression above references the argument to the
constructor, nombre. Once the constructor has returned, nombre stays in
memory so that its value can be used for the alert call. If nombre was
provided as a property (i.e. this.nombre) solely for use with
MuestraNombre, the code above makes that unnecessary.

Of course, this is a very specific example of the closure approach. It's
quite hard to give a generic example of things you can do with it.
Closures are a powerful feature of the Javascript language, and it's
worthwhile understanding them. The FAQ notes provides a detailed
description of how they work.

<URL:http://www.jibbering.com/faq/faq_notes/closures.html>

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Thank you very much :-)
Jul 23 '05 #6

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

Similar topics

1
by: Cyrus Lan | last post by:
I have a jar file, without source code, say abc.jar. I have set it in the CLASSPATH The main execute class in abc.jar is a.class. In the command prompt, I can execute the program by issuing...
18
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I...
0
by: Bartas | last post by:
Hi, I'am writting a simple SOAP client in python (2.4) using SOAPpy lib. I've met with this problem: when I want to send a list of complex type using some method from WebService(java,WAS), ...
9
by: PyPK | last post by:
Hi if I have a function called tmp=0 def execute(): tmp = tmp+1 return tmp also I have def func1(): execute() ....
6
by: RA | last post by:
Hi I have a windows form app and I need to execute a program when the user chooses an option. How do I start a program from code, with command line arguments and getting the return value from...
3
by: Sophos | last post by:
Hi, I have a basic aspx page, in the Page_Init procedure I have a server.execute of another aspx page that adds some html code to my first page. However it also adds a control (an htmlimage),...
3
by: Russell Verdun | last post by:
From a vb.net application I'm want to execute an Oracle Stored Procedure via a web service. What would be the best way to approach this? I can't pass and Oracle Command or the parameter objects...
3
by: RAG2007 | last post by:
I'm using the QueryDef and Execute method to update a record in my MySQL backend. Problem: When the Passthrough update query is defined using QueryDef, it becomes a select query, and I cannot use...
7
by: Jeff | last post by:
I need a way to do the following and cannot seem to find a solution via google. 1. Have a method from the main app to get all open forms 2. Check each open form for a public method 3. If this...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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
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
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...

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.