JSFiddle - React, Tailwind, and code Playground

by Bryan Braun

CSS

/*
The issue:
The `increment` method does not increment the exposed property value, but the incrementThis method does.

Why?
You cannot update an object's property from an object's method without using the self-referential keyword `this`.

I already knew that. What's the big deal?
The revealing module pattern makes it less obvious for a few reasons.
1. `count` is a variable and only becomes a property when revealed in the return statement. It's easy to get mixed up, and refer to the variable count (not using `this`) instead of the property count (using `this`).
2. You actually CAN increment the count variable using closures. But incrementing the variable does not increment the property because the property and variable are not linked. The property is assigned when the module is instantiated, and they are separate from that point on.

@todo: Improve this demo to use a better tool than alert boxes.
*/

JavaScript

var counter = (function() {
  var count = 0;
  
  function increment() {
	count = count + 1;
  }
  
  function printCountVar(text) {
    alert(text + count);
  }
  
  function incrementThis() {
    this.count = this.count + 1;
  }
    
  return {
  	increment: increment,
    incrementThis: incrementThis,
    count: count,
    printCountVar: printCountVar
  };
})();

alert('Original count property: ' + counter.count);
counter.printCountVar('Original count variable: ');
counter.increment();
alert('Count property after increment: ' + counter.count);
counter.printCountVar('Count variable after increment: ');
counter.incrementThis();
alert('Count proprety after incrementThis: ' + counter.count);
counter.printCountVar('Count variable after incrementThis: ');
// Note ^ if incrementThis actually incremented the variable than the count value would be 2 (instead of 1).