Day 13: MDN Sometimes Kind of Sucks (For Beginners)

Right after the wonderful explanation on JavaScriptisSexy.com, I went straight to MDN’s article on the .bind() function method to crystallise the concepts. And boy, did it not do that. Their first example, from a beginner’s perspective, is a mess.

this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX(); // 9, because in this case, "this" refers to the global object

// Create a new function with 'this' bound to module
//New programmers (like myself) might confuse the global var getX with module's property getX
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81

My main issue is the fact that they add a number of sticky points in their example that only adds to the confusion, and that you have to mentally untangle before understanding what should be a simple example.

  • module.getX(); is a method/function call with zero arguments being passed, although you could pass arguments into the method call like so, module.getX(9, 2, 4) and it wouldn’t matter. But it’s definitely a call on the function. Which is definitely not the same as module.getX which returns only the value of the property getX. And the value of the property getX is an uninvoked function i.e. function(){…}. And that’s why your this value inside the function changes to the global this referred in the top line, when you call retrieveX();. Of course, leaving out the above explanation makes it very difficult for a beginner to follow, so that really kind of sucked.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s