#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Function invocation patterns

In JavaScript, the way you call a function decides what this refers to inside it. The same function can behave differently depending on whether it is called on its own, as a method, with new, or through call, apply or bind. These are the function invocation patterns. Knowing them explains many confusing undefined errors and prepares you for arrow functions, which break the rules on purpose.

Pattern 1: plain function call

When you call a function by itself, like showName(), this is undefined in strict mode (which modules and classes use automatically). In old non-strict scripts, it falls back to the global object, window in browsers. Either way, it is rarely what you want.

Pattern 2: method call

When you call a function as a property of an object, like user.showName(), this is the object before the dot. The function itself does not belong to the object permanently; this is decided at the moment of the call.

'use strict';

function showName() {
  return this ? this.name : 'no this';
}

const user = { name: 'Meera', showName };
const admin = { name: 'Kabir', showName };

console.log(user.showName());   // "Meera"   - method call
console.log(admin.showName());  // "Kabir"   - same function, other object
console.log(showName());        // "no this" - plain call

const detached = user.showName;
console.log(detached());        // "no this" - lost its object

Pattern 3: constructor call with new

Calling a function with new creates a fresh empty object, sets its prototype to the function's prototype, runs the function with this pointing at that new object, and returns it automatically unless the function returns a different object. Classes use this pattern under the hood.

Pattern 4: call, apply and bind

These methods let you choose this yourself.

function introduce(greeting, punctuation) {
  return `${greeting}, I am ${this.name}${punctuation}`;
}

const dev = { name: 'Arjun' };

introduce.call(dev, 'Hello', '!');      // arguments listed one by one
introduce.apply(dev, ['Hi', '.']);      // arguments as an array

const boundIntro = introduce.bind(dev, 'Hey');
boundIntro('?');                        // "Hey, I am Arjun?"

function Counter() {
  this.count = 0;
}
const c = new Counter();                // constructor call
console.log(c.count);                   // 0

bind does not call the function; it returns a new one with this and optionally some arguments fixed. A bound function keeps that this no matter how it is later called.

Summary of the patterns

How it is calledValue of this
fn()undefined in strict mode
obj.fn()obj
new Fn()the newly created object
fn.call(x) / fn.apply(x)x
fn.bind(x)()x, permanently

Losing this when passing methods around

The most frequent bug is passing a method as a callback: setTimeout(user.showName, 100) or button.addEventListener('click', cart.clear). Only the function is passed, not the object, so it runs as a plain call (or, for DOM listeners, with this set to the element). Fix it with cart.clear.bind(cart) or a wrapper arrow: () => cart.clear().

Forgetting new with an old-style constructor function is another. Counter() without new runs as a plain call, so in strict mode this.count = 0 throws. Classes protect you by refusing to be called without new.

Classes add one more case. Methods in a class body run in strict mode, so a detached method called on its own gets undefined for this and throws as soon as it touches a property. That error, "Cannot read properties of undefined", is usually your clue that a method lost its object somewhere between definition and call.

What to take away

Look at the call site, not the definition, to work out this: what is before the dot, whether new is used, or whether call, apply or bind set it. When passing a method somewhere else, bind it or wrap it.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course