Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Last active August 29, 2015 14:06
Show Gist options
  • Save jasonrhodes/cfe4e6ef074539346e9e to your computer and use it in GitHub Desktop.
Save jasonrhodes/cfe4e6ef074539346e9e to your computer and use it in GitHub Desktop.
JS core concepts, useful for brushing up before interviews, etc.

Event delegation

DOM events bubble up through the DOM tree and register against every element up to the top. The object passed to the listener (call it e for example) will have the e.target property, which was the element that was interacted with directly ("clicked", etc.) and the e.currentTarget property, which is the element that was listening when this event listener caught the event.

e.stopPropagation() will keep the event from continuing to bubble up the DOM tree.


this

Starts off global. Inside function definitions, it's undefined unless it's been set by other methods (see below).

  • In object methods like myObject.doSomething(), this will be set to myObject.
  • Use fn.call(context), fn.apply(context), or fn.bind(context) to deliberately set the value of this

Prototype inheritance

P much everything has a prototype, kinda like a parent. If you call for a property using me.property or me.function(), JS will look at me and all of my prototype parents to see if that property/function exists and use the first one it finds.


AMD vs CommonJS

AMD uses define() and looks very async, while CommonJS uses just the require() method and looks incredibly sync.

// AMD
define('mymodule', ['dep1', 'dep2', 'dep3'], function (dep1, dep2, dep3) { 

  // module definition

}); 

// CommonJS
var dep1 = require("dep1");
var dep2 = require("dep2");
var dep3 = require("dep3");

module.exports = function () {
  
  // module definition

};

For AMD, think requireJS and for CommonJS think of how Node.js works.


Closures

You have access to the variables in your current function and everything up from there, but if you use one function to create another, and the resulting function had access to variables at its creation, it will always have access to those variables for its whole life.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment