SSJS: What’s „this“?

In Serverside JavaScript the keyword this always refers to the “owner” of the function which is executing,  or rather, to the object that a function is a method of.

This means f.e. that this refers to the UIComponent which contains the SSJS code. If you add a label to a XPage and compute the value…

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
   <xp:label id="label1">
      <xp:this.value>
         <![CDATA[#{javascript:return this;}]]>
      </xp:this.value>
   </xp:label>
</xp:view>

this will always return the current corresponding instance of the XspOutputLabel:

But if you are inside a function this will return the current JavaScript object instead:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

   <xp:label id="label1">
      <xp:this.value>
         <![CDATA[#{javascript:
            var arr = [1, 2];

            function callMe(){
               var obj = this;
               for( var p in obj ){
                  print( p + " -> " + obj[p] + " [" + typeof(obj[p]) + "]" );
               }    
            }
            callMe()
         }]]>
      </xp:this.value>
   </xp:label>

</xp:view>

The result on the console looks like this:

If you are using call or apply, you can overwrite the this object:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

   <xp:label id="label1">
      <xp:this.value>
         <![CDATA[#{javascript:
            function callMe(){
               println(this);

               for( p in arguments ){
                  println( arguments[p] );
               } 
            }

            callMe.call("1","2","3");
         }]]>
      </xp:this.value>
   </xp:label>
</xp:view>

Now this is set to „1„. The arguments are „2“ and „3„, as you can see on the server console:

Dieser Beitrag wurde unter Allgemein, Java Script, ServerSide JavaScript, XPages abgelegt und mit , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Eine Antwort zu SSJS: What’s „this“?

  1. Tim Tripcony sagt:

    Also keep in mind that, while this refers to the component in value bindings, in event handlers it refers to the event handler itself. So top-level code (i.e. not in a function) in an event handler can use this.getParent() to refer to the component to which the event handler is bound.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert