Execute an instance method

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jesús Ángel

    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:


    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.onclic k=this.muestraN ombre;

    Thanks. And excuse my poor english.

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

    this.div=docume nt.createElemen t('div');
    this.div.style. border='1px solid #000';
    this.div.style. width='10px';
    this.div.style. height='10px';

    this.div.onclic k=this.muestraN ombre;
    // Esto no funciona, la función se ejecuta pero
    // la referencia this se pierde y aparece 'undefined'

    var body=document.g etElementsByTag Name('body').it em(0);
    body.appendChil d(this.div);

    }
    function MuestraNombre() {
    alert(this.nomb re);
    }
    Objeto.prototyp e.muestraNombre =MuestraNombre;
    </script>
    </head>
    <body>
    <script type="text/javascript">obj 1=new Objeto('Objeto1 ');</script>
    <p></p>
    <script type="text/javascript">obj 2=new Objeto('Objeto2 ');</script>
    </body>
    </html>
  • Martin Honnen

    #2
    Re: Execute an instance method



    Jesús Ángel wrote:

    [color=blue]
    > function Objeto(nombre) {
    > this.nombre=nom bre;
    >
    > this.div=docume nt.createElemen t('div');[/color]

    this.div.objeto = this;
    [color=blue]
    > this.div.style. border='1px solid #000';
    > this.div.style. width='10px';
    > this.div.style. height='10px';
    >
    > this.div.onclic k=this.muestraN ombre;
    > // Esto no funciona, la función se ejecuta pero
    > // la referencia this se pierde y aparece 'undefined'
    >
    > var body=document.g etElementsByTag Name('body').it em(0);
    > body.appendChil d(this.div);
    >
    > }
    > function MuestraNombre() {
    > alert(this.nomb re);[/color]

    alert(this.obje to.nombre);



    --

    Martin Honnen

    Comment

    • Michael Winter

      #3
      Re: Execute an instance method

      On Thu, 23 Sep 2004 18:41:22 +0200, Jesús Ángel
      <NOjesusangelSP AM@computer.org > wrote:

      [snip]
      [color=blue]
      > The following sentence doesn't work.
      >
      > this.div.onclic k=this.muestraN ombre;[/color]

      [snip]
      [color=blue]
      > function MuestraNombre() {
      > alert(this.nomb re);
      > }
      >
      > Objeto.prototyp e.muestraNombre =MuestraNombre;[/color]

      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.prototyp e.toString = function() {return '[Objeto]';};

      this at the end of the script:

      var testObject = new Objeto('test');
      testObject.mues traNombre();

      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.
      [color=blue]
      > this.div=docume nt.createElemen t('div');
      > this.div.style. border='1px solid #000';
      > this.div.style. width='10px';
      > this.div.style. height='10px';[/color]

      Why don't you create a CSS rule with a class selector specifying those
      property values, and give the new DIV that class name?
      [color=blue]
      > var body=document.g etElementsByTag Name('body').it em(0);[/color]

      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.

      Comment

      • Jesús Ángel

        #4
        Re: Execute an instance method

        > What you've attempted in your original post can be achieved in three[color=blue]
        > 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.[/color]

        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=docume nt.createElemen t('div');
        this.div.classN ame='divExample '

        // First way
        this.div.object =this;
        this.div.onclic k=function() { this.object.sho wName() };
        /*
        // Second way
        eval ('this.div.oncl ick=function() { '+this.name+'.s howName() };');
        */

        var body=document.b ody;
        body.appendChil d(this.div);

        }
        function showName() {
        alert(this.name );
        }
        Object.prototyp e.showName=show Name;
        </script>
        </head>
        <body>
        <script type="text/javascript">Obj ect1=new Object('Object1 ');</script>
        <p></p>
        <script type="text/javascript">Obj ect2=new Object('Object2 ');</script>
        </body>
        </html>

        Comment

        • Michael Winter

          #5
          Re: Execute an instance method

          On Mon, 27 Sep 2004 10:31:58 +0200, Jesús Ángel
          <NOjesusangelSP AM@computer.org > wrote:

          [I wrote this:][color=blue][color=green]
          >> 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.[/color][/color]

          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]
          [color=blue]
          > Can you please post a message with an example of the third way (using a
          > closure).[/color]

          Certainly.

          [snip]

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

          // Rest of your code

          // This is your MuestraNombre function
          this.div.onclic k = 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.c om/faq/faq_notes/closures.html>

          Good luck,
          Mike

          --
          Michael Winter
          Replace ".invalid" with ".uk" to reply by e-mail.

          Comment

          • Jesús Ángel

            #6
            Re: Execute an instance method

            Thank you very much :-)

            Comment

            Working...