JS Syntax
  • Introduction
  • this
  • block-level scope
  • ===
  • inefficient DOM manipulation
  • Reference equality, shallow equality and deep equality
  • D3 - 2
  • D3 - 5
  • D3 - static
Powered by GitBook
On this page
  • Traditional solution
  • New solution

Was this helpful?

this

Game.prototype.restart = function () {
  this.clearLocalStorage();
  this.timer = setTimeout(function() {
    this.clearBoard();    // what is "this"?
  }, 0);
};

error: Uncaught TypeError: undefined is not a function

When you invoke setTimeout(), you are actually invoking window.setTimeout(). Therefore, this.clearBoard(); refers to the window object.

Traditional solution

  • use var self = this;

Game.prototype.restart = function () {
  this.clearLocalStorage();
  var self = this;   // save reference to 'this', while it's still this!
  this.timer = setTimeout(function(){
    self.clearBoard();    // oh OK, I do know who 'self' is!
  }, 0);
};

New solution

  • use the bind() method to pass in the proper reference:

Game.prototype.restart = function () {
  this.clearLocalStorage();
  this.timer = setTimeout(this.reset.bind(this), 0);  // bind to 'this'
};

Game.prototype.reset = function(){
    this.clearBoard();    // ahhh, back in the context of the right 'this'!
};
PreviousIntroductionNextblock-level scope

Last updated 5 years ago

Was this helpful?