Sign in

Javascript Instance Method apply, bind, call. Javascript Function call back, closure

I have a hard time understanding and remember these Javascript Objects, Instance Methods, and Functions because I don’t use them daily. So I hope this will help you to refresh your memory.

We use objects to store multiple values as a data structure.

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

const numbers = [5, 6, 2, 3, 7];const max = Math.max.apply(null, numbers);console.log(max);
// expected output: 7
const min = Math.min.apply(null, numbers);console.log(min);
// expected output: 2

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.

const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

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"

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

function greeting(name) {
alert('Hello ' + name);
}

function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}

processUserInput(greeting);

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();

References:

https://developer.mozilla.org/en-US/docs/Glossary