This
Menu This
 

The Javascript "this" keyword

You will see "this" used in many JavaScripts you may be trying to work out what they do and how they work.

My interpretation is that "This" the current object instance? There are many ways of looking at it.

From my observations of some the JavaScript for the Accessible Carousel there are many methods that access the "owner" of the object (I guess?)

Top

What W3C say:

The JavaScript this keyword refers to the object it belongs to.

It has different values depending on where it is used:

  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

As Douglas Crockford says (I think) is not really that clear.

"this" in PHP

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). As of PHP 7.0.0 calling a non-static method statically from an incompatible context results in $this being undefined inside the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0. As of PHP 7.0.0 calling a non-static method statically has been generally deprecated (even if called from a compatible context). Before PHP 5.6.0 such calls already triggered a strict notice.

Carousel.prototype.updateRotation - updateRotation method

Carousel.prototype.updateRotation = function () {

  if (!this.hasHover && !this.hasFocus && !this.isStopped) {
    this.rotate = true;
    this.liveRegionNode.setAttribute('aria-live', 'off');
  }
  else {
    this.rotate = false;
    this.liveRegionNode.setAttribute('aria-live', 'polite');
  }

  if (this.isStopped) {
    this.pauseButton.setAttribute('aria-label', this.playLabel);
    this.pauseButton.classList.remove('pause');
    this.pauseButton.classList.add('play');
  }
  else {
    this.pauseButton.setAttribute('aria-label', this.pauseLabel);
    this.pauseButton.classList.remove('play');
    this.pauseButton.classList.add('pause');
  }
};

Links

Top

References: - a note on these

  • The JavaScript this Keyword - https://www.w3schools.com/js/js_this.asp
  • this in PHP - https://www.php.net/manual/en/language.oop5.basic.php

Site design by Tempusfugit Web Design -