JSFiddle - React, Tailwind, and code Playground

by Joel Lubrano

JavaScript

/**
 * Option 1: bind before passing to setTimeout
 * Option 2: bind within class itself 
 */

var Foo = function() {
    this.bar = "bar";
    
    // option 1 - part a
    this.baz = function() {
        alert(this.bar);
    };
    
    // option 2 - part a
    this.bound = (function() {
        alert(this.bar);
    }).bind(this);
}

var foo = new Foo();

// works fine
foo.baz();

// won't work
setTimeout(foo.baz, 500);

// option 1 - part b
var bound = foo.baz.bind(foo);
setTimeout(bound, 1000);
// end option 1

// option 2 - part b
setTimeout(foo.bound, 1500);