Skip to content

Instantly share code, notes, and snippets.

@agnellvj
Last active October 5, 2017 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agnellvj/5cb62c4a0ee2cde9dfd02542182ac737 to your computer and use it in GitHub Desktop.
Save agnellvj/5cb62c4a0ee2cde9dfd02542182ac737 to your computer and use it in GitHub Desktop.

sources

Functions

  1. Use case can include a database connection as the first argument
function curries(fn) {
  const args = Array.prototype.slice.call(arguments, 1);

  return function() {
    return fn.apply(this, args.concat(Array.prototype.slice.call(arguments, 0)));
  }
}

const sequence = (start, end) => {
    let result = [];
    for(let i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
};

let seq5 = curries(sequence, 1);

seq5(5) 

(5) [1, 2, 3, 4, 5]

Function Declarations

funcDeclaration() {
  return 'A function declaration';
}
  1. Can be overridden, hoisted, shadowed... etc.

Function Expressions

const funcExpression = () => {
  return 'A function expression';
}
  1. Closures
  2. IIFE

Generators

const funcGenExpr = function* () => {
  yield 42;
};

javascript functions

While the syntax of apply() is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

apply()

bind()

Define / shim bind if not already defined
Function.prototype.bind = Function.prototype.bind || function(context){
  var self = this;

  return function(){
    return self.apply(context, arguments);
  };
}

call()

Objects

this

  1. In the global context or inside a function this refers to the window object.
  2. Inside IIFE (immediate invoking function) if you use "use strict", value of this is undefined. To pass access window inside IIFE with "use strict", you have to pass this.
  3. While executing a function in the context of an object, the object becomes the value of this
  4. Inside a setTimeout function, the value of this is the window object.
  5. If you use a constructor (by using new keyword) to create an object, the value of this will refer to the newly created object.
  6. You can set the value of this to any arbitrary object by passing the object as the first parameter of bind, call or apply
  7. For dom event handler, value of this would be the element that fired the event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment