» Quick Introduction to JavaScript » 2. Advanced » 2.1 Context


In JavaScript, there're three contexes you need to care about:

  • Function Context
  • Class Context
  • Global Context


The this keyword in JavaScript refers to the object to which a function belongs, or the object that is currently executing the function. In most cases, the value of this depends on how a function is called.

In a function

function showThis() {

// In this case, 'this' refers to the global object

Inside an Object Method

const myObject = {
  property: "I'm a property",
  method: function () {

// 'this' inside the method refers to the object (myObject)


The bind() method in JavaScript is used to create a new function that, when called, has its this keyword set to the provided value. It's often used to explicitly set the context of a function.

const m = {
  x: 42,
  getX: function () {
    return this.x;

const unboundGetX = m.getX;
// The function gets invoked at the global scope
// Expected output: undefined

const boundGetX = unboundGetX.bind(m);
// Expected output: 42

The bind() function creates a new bound function. Calling the bound function generally results in the execution of the function it wraps, which is also called the target function.


The apply() method in JavaScript is used to invoke a function with a given this value and an array or array-like object of arguments.

// Define a function that uses 'this'
function greet(age) {
  console.log(`Hello, ${this.name}! You are ${age} years old.`);

// Create an object to use as the 'this' value
const person = {
  name: 'John',
  age: 30

// Use apply() to invoke the greet function with the person object as 'this'
// and an array as arguments
greet.apply(person, [25]);

Code Challenge

Your task is to implement a simplified version of the bind() method. Create a function called customBind that mimics the behavior of bind(). The customBind function should take two arguments:

  1. The object to which this should be set.
  2. The function to be called.

The customBind function should return a new function that, when called, invokes the original function with the specified context.

Note: you may use ...args syntax to capture any arguments passed to the new function.

> code result goes here