Skip to content

Instantly share code, notes, and snippets.

@vishnu-saini
Last active July 31, 2018 09:46
Show Gist options
  • Save vishnu-saini/4033889f74d6671f789a9af836a1418c to your computer and use it in GitHub Desktop.
Save vishnu-saini/4033889f74d6671f789a9af836a1418c to your computer and use it in GitHub Desktop.
  1. The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. Function.prototype.bind()
    var module = {
      x: 42,
      getX: function() {
        return this.x;
      }
    }
    
    var unboundGetX = module.getX;
    console.log(unboundGetX()); // The function gets invoked at the global scope
    // expected output: undefined
    
    var boundGetX = unboundGetX.bind(module);
    console.log(boundGetX());
    // expected output: 42
    
  2. The call() method calls a function with a given this value and arguments provided individually.
    function Product(name, price) {
      this.name = name;
      this.price = price;
    }
    
    function Food(name, price) {
      Product.call(this, name, price);
      this.category = 'food';
    }
    
    console.log(new Food('cheese', 5).name);
    // expected output: "cheese"
    
  3. The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
    var numbers = [5, 6, 2, 3, 7];
    
    var max = Math.max.apply(null, numbers);
    
    console.log(max);
    // expected output: 7
    
    var min = Math.min.apply(null, numbers);
    
    console.log(min);
    // expected output: 2
    

Note: While the syntax of this function 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.

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