completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Function calls: [[Call]] & [[Construct]]

Trace how ECMAScript calls and constructs functions, binds this, initializes parameters, handles classes and bound functions, and routes Proxy traps.

By the end, you can
  • 01
    Follow a plain callName the three jobs of a call: make a new context, pick this, and run the body after its names are set up.
  • 02
    Follow a call with newTell a base class from a derived class, and explain how new.target picks the new object's prototype.
  • 03
    Spot wrappersPredict what bind, Proxy, and Reflect do with a plain call and with new.

Two ways to run a function

In the execution contexts lesson, each call put a new context on the stack. This lesson asks a different question: what starts the call? The specification (the rule book for JavaScript, also called the spec) answers with two hidden steps that a function can have:

  • [[Call]] runs the function when you call it, like greet("Asha").
  • [[Construct]] runs it with new, like new Order("tea"). Not every function has it.
A plain function callPop out in the code editor (opens in a new tab)JavaScript
function greet(user) {
  return "Hi, " + user;
}
console.log(greet("Asha"));

Line 1 makes a function called greet. It has one parameter, user: a name for the value the caller passes in. Line 2 gives back a greeting with that name in it. Line 4 calls greet with "Asha" and prints Hi, Asha. Your code never writes [[Call]]. The round brackets after greet are enough, and JavaScript uses [[Call]] for you.

The main idea

An internal method is a step the spec gives an object. Its name is written in double square brackets. A plain call uses [[Call]]. A call with new uses [[Construct]], if the function has one. Neither one is a property: greet["[[Call]]"] doesn't give you anything.

The two ways give back different things:

  • A plain call can give back any value: a number, a string, or an object.
  • A call with new always gives back an object, or it throws an error.
Left: greet("Asha") goes through [[Call]] and gives back the string "Hi, Asha". Right: new Order("tea") goes through [[Construct]] and gives back an object with item: "tea".greet("Asha")[[Call]]"Hi, Asha"any value backnew Order("tea")[[Construct]]{ item: "tea" }always an object
A plain call uses [[Call]] and can give back any value, like a string. A call with new uses [[Construct]] and always gives back an object.

Your code can't see these hidden steps. So this lesson runs tiny programs and looks at what they print.

What a function keeps inside

In JavaScript, a function is an object. The spec calls it a function object. Besides the code to run, it keeps some hidden facts that the spec needs. Each hidden fact sits in an internal slot: a named place that only the spec can use. Its name is also written in double square brackets, and it is not a property.

A function made with the function keyword can be called, and it can also be used with new. Not every function can do both. You'll see the ones that can't later in the lesson.

One function, called with newPop out in the code editor (opens in a new tab)JavaScript
function Order(item) {
  this.item = item;
}
console.log(typeof Order, new Order("tea").item);

Line 1 makes a function called Order. Line 2 stores the item on this, the object the function is working on. Line 4 prints two things:

  • typeof Order gives function. (typeof tells you what kind of value something is.)
  • new Order("tea") makes a new object, and its item is tea.

So the output is function tea. The output shows what Order does. It doesn't show any hidden slot.

The table below lists five hidden slots. Read each row as: "the spec keeps this, for this reason, but it is not that."

Five hidden slots a function keeps
Slot nameWhy the spec keeps itWhat it is not
[[Environment]]The scope the function was made in, so it can find names from outside it.Not a property you can read on the function.
[[FormalParameters]]The list of parameters, used when a call starts.Not the values passed in, and not the function's length property.
[[ECMAScriptCode]]The body: the code that each call runs.Not a string that is read again on every call.
[[ThisMode]]How a call picks this: LEXICAL, STRICT, or GLOBAL.Not about whether the calling code uses strict mode, and not the function's name.
[[ConstructorKind]]BASE or DERIVED: whether new makes the object before the body runs.Not the constructor property you can read on an object.

The spec's table of function slots lists a few more, such as [[Realm]], [[ScriptOrModule]], and [[IsClassConstructor]]. Two slots matter most for a call:

  • [[Environment]] is the scope the function was made in. It lets the function find names from outside it.
  • [[FormalParameters]] and [[ECMAScriptCode]] are the parameters and the body. They tell a call what to run.

The slots describe what JavaScript must do. They don't say how a real engine lays out its memory.

Real-life analogyA home kitchen and its cook

A cook knows a recipe before any order comes in. Each order brings the ingredients for one dish. The cook uses the same recipe every time, with the new ingredients.

In real life: The cook knows a recipe
In JavaScript: A function keeps its code
In real life: An order lists the ingredients
In JavaScript: The call passes in values
In real life: The cook makes one dish
In JavaScript: The call runs the body once

What a plain call does first

When you call a function, [[Call]] does three jobs, in this order:

  1. PrepareForOrdinaryCall makes a new context for this call, with its own place for the parameters. The code that made the call waits.
  2. OrdinaryCallBindThis picks the value of this for the call. How it picks depends on a slot called [[ThisMode]].
  3. OrdinaryCallEvaluateBody runs the body of the function.
A call that adds a fee to a pricePop out in the code editor (opens in a new tab)JavaScript
function addFee(price) {
  return price + 2;
}
console.log(addFee(3));

Line 1 makes a function called addFee, with a parameter called price. Line 2 adds 2 and gives back the sum. Line 4 calls it with 3 and prints 5. Each call gets its own fresh price. A second call would not see the first call's price.

The next box shows spec steps. Spec steps read like a recipe, one step per line:

  • "Let x be …" means "do this, and call the result x".
  • "Perform …" means "do this step".
  • A ? before a step means "if this step fails, stop and throw the error".

Here are three lines from the spec's [[Call]] steps for a normal function. func is the function being called, and argList is the list of values passed in.

How [[Call]] runs a function, three lines from the specText
"Let calleeContext be PrepareForOrdinaryCall(func, undefined)."
"Perform OrdinaryCallBindThis(func, calleeContext, thisArg)."
"Let result be Completion(OrdinaryCallEvaluateBody(func, argList))."

In plain words, line by line:

  1. Make a new context for the call, and call it calleeContext.
  2. Pick the value of this and store it in that new context.
  3. Run the body with the values passed in, and keep what happens as result.

The lines come from the spec's [[Call]] steps for a normal function. The steps left out handle classes and put the caller back on top when the call ends. The caller comes back even if the body throws an error.

Calling addFee(3) in three steps, left to right. Step 1, new context: a place for price. Step 2, set this. Step 3, run the body, which gives back 5.addFee(3)1. new context2. set this3. run bodya place for pricethis for the callgives back 5
[[Call]] does the three steps from the box, in order. The body runs last, and gives back 5.
Step through a plain call
Step 0 of 4Ready
Your turn: follow the blue line

A replay of the lesson's addFee code. It doesn't show the inside of an engine.

Running in
  1. script
Next: line 4
function addFee(price) {  return price + 2;}
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Step through the real addFee call. First the caller calls. Then price gets 3. Then the body gives back 5. Last, the caller prints it. This is a recording of the lesson's code, not a view inside a real engine. Back shows the step before.

Two calls of one method, with a different thisPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3, show() { return this.price; } };
console.log(cart.show());
console.log(Reflect.apply(cart.show, { price: 5 }, []));

Line 1 makes a cart with a price of 3 and a method, show, that gives back this.price. Line 2 calls cart.show(), so this is the cart, and it prints 3. Line 3 uses Reflect.apply. It calls a function with a this you choose and a list of values. Here this is { price: 5 }, so it prints 5. The body is the same. Only this changed.

Three ways to pick this

The [[ThisMode]] slot has one of three values. Each one picks this in its own way:

  • STRICT, for a function in strict mode: this is exactly the value the call passed. A call with no object before the dot passes undefined.
  • GLOBAL, for a normal function outside strict mode: null or undefined becomes the global object. A number or string is wrapped in an object.
  • LEXICAL, for an arrow function: the arrow gets no this of its own. It uses the this of the code around it.
In strict mode, this stays undefinedPop out in the code editor (opens in a new tab)JavaScript
function strictThis() {
  "use strict";
  return this;
}
console.log(strictThis() === undefined);

Line 1 makes a function called strictThis. Line 2, "use strict", turns on strict mode for its body. Line 3 gives back this. Line 5 calls it with nothing before the dot, so this is undefined, and it prints true.

Outside strict mode, this gets swappedPop out in the code editor (opens in a new tab)JavaScript
function looseThis() {
  return this;
}
console.log(looseThis.call(null) === globalThis);
console.log(typeof looseThis.call(3));

Lines 1 to 3 make a function outside strict mode that gives back this. The .call() method calls a function and passes its first value as this. Line 4 passes null, but this becomes globalThis, the global object, so it prints true. Line 5 passes the number 3. It gets wrapped in an object, so typeof prints object. The swap happens inside the called function, when it picks this.

An arrow uses the this around itPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3, makeReader() { return () => this.price; } };
const readPrice = cart.makeReader();
console.log(readPrice.call({ price: 5 }));

Line 1 makes a cart with a method, makeReader, that makes and gives back an arrow. Line 2 calls cart.makeReader(), so the method's this is the cart, and saves the arrow. Line 3 tries to pass a different this with .call(), but it still prints 3. The arrow uses the this of the method it was made in, and that was the cart.

For every case, see OrdinaryCallBindThis and OrdinaryFunctionCreate in the spec. The mode belongs to the function being called. It doesn't matter whether the code that calls it uses strict mode.

How the body starts

The third job of a call is OrdinaryCallEvaluateBody. It takes the body kept in the [[ECMAScriptCode]] slot and hands it to EvaluateBody. EvaluateBody has a different set of steps for each kind of function:

  • a normal function
  • an arrow function
  • a generator (a function with * that can pause)
  • an async function (a function that can wait with await)

This lesson only follows the normal function, so each step does one job.

A function that gives back its itemPop out in the code editor (opens in a new tab)JavaScript
function getItem(item) {
  return item;
}
console.log(getItem("tea"));

Line 1 makes a function called getItem, with a parameter called item. Line 2 gives back item. Line 4 calls it with "tea" and prints tea. Before line 2 can run, item must already hold "tea". Something has to set that up first. The spec shows what.

The box below has two lines from two different spec steps. In the first line, func is the function being called. In the second line, the spec calls the same function funcObj.

How the body starts, two lines from the specText
"Return ? EvaluateBody of func.[[ECMAScriptCode]] with arguments func and argList."
"Perform ? FunctionDeclarationInstantiation(funcObj, argList)."

In plain words, line by line:

  1. Run the steps for this kind of body, with the function and the values passed in. Give back what they give back.
  2. Before the first line of the body, set up the parameters and the other names in the function. If that fails, stop and throw.

Line 1 is from OrdinaryCallEvaluateBody. Line 2 is from EvaluateFunctionBody, the steps for a normal function body. The full steps also say how the function gives back its value, or stops early with an error.

So a call splits its work into clear parts. The call sets up the context and this. EvaluateBody picks the steps for the kind of body. Setting up the names comes first inside those steps. Your code never calls any of these names. They only describe what JavaScript does.

Setting up names before the body: hoisting

FunctionDeclarationInstantiation is the spec step that sets up a call's names before the first line of the body runs. A new set is made for every call. Each kind of name is set up in its own way:

  • A parameter gets the value the caller passed in.
  • A function made with the function keyword inside the body gets its function, ready to call.
  • A var name gets undefined for now.
  • A let or const name exists, but has no value yet. Reading it throws an error until its line runs.

People often call this hoisting: names seem to be "lifted" to the top of the function. This step is what really happens.

A function is ready, but a var still holds undefinedPop out in the code editor (opens in a new tab)JavaScript
function receipt(item) {
  console.log(label(item), fee);
  var fee = 2;
  function label(value) { return "Item: " + value; }
}
receipt("tea");

Line 1 starts the function receipt. Line 2 calls label(item) and prints it together with fee. Line 3 sets fee to 2, but it hasn't run yet when line 2 prints. Line 4 makes the label function, which was already set up before line 2. Line 6 calls receipt with "tea". The output is Item: tea undefined.

Three boxes made before line 2 runs. Box item holds "tea". Box label holds the label function. Box fee holds undefined.made before line 2 runs"tea"itemparameterlabel()labelfunctionundefinedfeevar
Before line 2 runs, all three names exist. item and label already have their values, but fee still holds undefined, because line 3 has not run yet.

The spec's FunctionDeclarationInstantiation steps treat parameters, var names, let and const names, and inner functions each in their own way. If two inner functions have the same name, the last one wins. Nothing really moves to the top: the line var fee = 2 on line 3 still runs in its own place, after line 2.

A default value is set up with the parametersPop out in the code editor (opens in a new tab)JavaScript
function total(price = 3) {
  return price + 2;
}
console.log(total());

Line 1 gives price a default value of 3: the value it gets when the caller passes nothing. Line 2 gives back price plus 2. Line 4 calls total() with nothing, so price gets 3 while the parameters are set up, and it prints 5.

When a function has default values, the spec may make a second, separate place for the names in the body. Then a function made inside a default value can't see a name that the body makes later.

A let name can't be read before its linePop out in the code editor (opens in a new tab)JavaScript
function readEarly() {
  console.log(typeof price);
  let price = 3;
}
try { readEarly(); } catch (error) { console.log(error.name); }

Line 1 makes the function readEarly. Line 2 asks for typeof price before line 3 gives price its value. Line 5 calls the function inside try, catches the error, and prints its name, ReferenceError. Even typeof can't read a let name before its line runs. A var name like fee above is different: it holds undefined from the start.

How to read a function, in order
  1. Look at the parameters and the values they get.
  2. Find every name the body makes: inner functions, var, let, and const.
  3. Note which names already have a value before the body starts.
  4. Then read the lines of the body from top to bottom.

A name can exist before the line that gives it a value.

What new does: [[Construct]] and new.target

A constructor is a function that has a [[Construct]] step, so you can use it with new. When you write new Order("tea"), JavaScript runs [[Construct]] and passes it one extra value, newTarget. newTarget is the constructor that new was used with. Here it is Order.

For a normal constructor like Order, [[Construct]] does three jobs, in this order:

  1. It makes a new, empty object.
  2. It makes that object the this of the call.
  3. It runs the body.
new makes an Order objectPop out in the code editor (opens in a new tab)JavaScript
function Order(item) {
  this.item = item;
}
console.log(new Order("tea").item);

Line 1 makes the function Order. Line 2 stores the item on this.item. Line 4 calls new Order("tea") and prints the new object's item, which is tea. Line 2 doesn't make the object. new made it before line 2 ran, and line 2 only adds item to it. Without new, no new object would be made.

Here are three lines from the spec's [[Construct]] steps for a normal function. func is the constructor being run.

How [[Construct]] starts, three lines from the specText
"Let kind be func.[[ConstructorKind]]."
"Let thisArg be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%")."
"Let calleeContext be PrepareForOrdinaryCall(func, newTarget)."

In plain words, line by line:

  1. Check what kind of constructor this is: a normal one (base) or a class that extends another (derived).
  2. Make the new object. Its prototype comes from newTarget. If that fails, stop and throw.
  3. Make a new context for the call, like a plain call does, and remember newTarget in it.

A prototype is another object that the new object looks in when it doesn't have a property itself. Line 2 uses OrdinaryCreateFromConstructor. It reads the prototype property of newTarget. If that property isn't an object, it uses the plain Object.prototype instead. The full [[Construct]] steps also set up class fields and decide what the call gives back.

Step through a call with new
Step 0 of 4Ready
Your turn: follow the blue line

A replay of the lesson's Order code. It doesn't show any hidden slots.

Running in
  1. script
Next: line 4
function Order(item) {  this.item = item;}console.log(order.item);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Step through the real construction. Line 4 starts it. Line 1 gets the item. Line 2 writes it on the new object. Line 5 reads the property. The recording runs the real Order function. It shows what the program does, not the inside of [[Construct]] or of an engine.

Change the order item
Order code, starting with teaPop out in the code editor (opens in a new tab)JavaScript
function Order(item) { this.item = item; }
const order = new Order("tea");
console.log(order.item);
The new object
order.item"tea"

Your text takes the place of "tea" on line 2 of the code.

Try it yourself

new Order("tea") makes a new object and puts item "tea" on it.

This runs the lesson's real Order function with your item. It doesn't show any hidden slots. Reset puts back tea.

Type a different item above, and see the new object's item change. Reset puts back tea. Your text takes the place of "tea" on line 2 of the code, and a real new Order is made with it. Empty text works too: it makes an empty string.

Read new.target inside OrderPop out in the code editor (opens in a new tab)JavaScript
function Order(item) {
  this.item = item;
  this.createdBy = new.target.name;
}
console.log(new Order("tea").createdBy);

Your code can read newTarget as new.target. Line 1 makes Order. Line 2 stores the item. Line 3 stores new.target.name, the name of the constructor that new was used with. Line 5 calls new Order("tea") and prints Order. Here newTarget and the running function are the same. The next example makes them different.

Pick a different prototype for the new objectPop out in the code editor (opens in a new tab)JavaScript
function Order(item) { this.item = item; }
function SpecialOrder() {}
SpecialOrder.prototype.kind = "gift";
const order = Reflect.construct(Order, ["tea"], SpecialOrder);
console.log(order.item, order.kind, order instanceof SpecialOrder);

Line 1 makes Order. Line 2 makes an empty function, SpecialOrder. Line 3 puts kind: "gift" on its prototype. Line 4 uses Reflect.construct. It works like new, but takes three things:

  • the function whose body runs: Order
  • the list of values to pass in: ["tea"]
  • the newTarget: SpecialOrder

Line 5 prints tea gift true. Order's body wrote item. The new object finds kind on SpecialOrder.prototype, so it is also an instanceof SpecialOrder.

The new object order holds item: "tea". An arrow from the Order card says it writes item. An arrow from the SpecialOrder card says it shares kind: gift through its prototype.item: "tea"orderOrderwrites itemSpecialOrdershares kind: gift
Order's body writes item on the new object. SpecialOrder picks its prototype, so the object also finds kind: "gift" there.
Real-life analogyA shopping list

First you pick a printed shopping-list form, maybe one with a "gift" box at the top. Then you write tea on it. Picking the form and writing on it are two separate jobs.

In real life: Pick a printed list form
In JavaScript: newTarget picks the prototype
In real life: Write tea on the form
In JavaScript: The body writes item
In real life: Hand over the filled-in form
In JavaScript: new gives back the object

Classes with and without extends

A class has a constructor too. There are two kinds:

  • A base class doesn't extends anything. Like Order above, it gets a new object as this before its body runs.
  • A derived class uses extends to build on a parent class. Its this has no value at first. It gets one only when the body calls super(), which runs the parent's constructor.
A base class gets a new objectPop out in the code editor (opens in a new tab)JavaScript
class Order {
  constructor(item) { this.item = item; }
}
console.log(new Order("tea").item);

Line 1 starts the class Order. Line 2 is its constructor: it gets item and stores it on this. Line 4 calls new Order("tea") and prints tea. Code inside a class is always in strict mode. That doesn't stop the constructor from using this, because new gave it an object.

A derived class calls super firstPop out in the code editor (opens in a new tab)JavaScript
class Order { constructor(item) { this.item = item; } }
class GiftOrder extends Order {
  constructor(item) {
    super(item);
    this.gift = true;
  }
}
console.log(new GiftOrder("tea").item);

Line 1 makes the base class Order. Line 2 makes GiftOrder, which extends Order. Line 4 calls super(item). That runs Order's constructor, which makes the object and stores item. Now this has a value, so line 5 can set this.gift. Line 8 calls new GiftOrder("tea") and prints tea. During super(), newTarget is still GiftOrder, so the object gets GiftOrder's prototype.

In the spec's [[Construct]] steps, only a base constructor makes an object before its body runs. A derived constructor starts with no value for this. The super() steps run the parent with the same newTarget, then give this the object that comes back.

Using this before super fails on purposePop out in the code editor (opens in a new tab)JavaScript
class Order {}
class GiftOrder extends Order {
  constructor() {
    this.gift = true;
    super();
  }
}
new GiftOrder();

Line 1 makes a base class. Line 2 makes a derived class. Line 4 tries to use this before line 5 calls super(). Line 8 calls new GiftOrder(). Line 4 throws a ReferenceError, so this.gift is never set. The error message is different in each browser, so only the error type matters.

Some functions can be called but not used with new

Being able to call a function is one thing. Being able to use it with new is another. Three cases show the difference:

  • A class has a [[Call]] step, but that step always throws a TypeError. So you must use new.
  • An arrow function has [[Call]] but no [[Construct]].
  • A short method, written as show() { } inside an object, also has [[Call]] but no [[Construct]].

Using new on an arrow or a short method throws a TypeError before the body starts. Each browser words the error message differently.

Calling a class without new fails on purposePop out in the code editor (opens in a new tab)JavaScript
class Order {}
Order();

Line 1 makes a class. Line 2 calls it without new, so it throws a TypeError. The class does have [[Call]]. Its [[Call]] step sees that it belongs to a class and throws on purpose.

Using new on an arrow fails on purposePop out in the code editor (opens in a new tab)JavaScript
const makeOrder = (item) => ({ item });
new makeOrder("tea");

Line 1 makes an arrow that gives back a new object. Line 2 tries new makeOrder("tea") and throws a TypeError. Giving back an object is not enough. Only a function with a [[Construct]] step works with new.

A short method can be calledPop out in the code editor (opens in a new tab)JavaScript
const cart = { show() { return "tea"; } };
console.log(cart.show());
console.log(Object.hasOwn(cart.show, "prototype"));

Line 1 makes a cart with a short method, show. Line 2 calls it and prints tea. Line 3 uses Object.hasOwn to check whether show has its own prototype property. It prints false. The short method is not a constructor. A property written as show: function () { } would be one. The spec's method steps never give a short method a [[Construct]] step.

Functions made with bind

The bind method makes a new function that wraps another one. The spec calls the new function a bound function exotic object. ("Exotic" just means it follows some special rules of its own.) It keeps three hidden slots:

  • [[BoundTargetFunction]]: the function it wraps.
  • [[BoundThis]]: the this to use for every call.
  • [[BoundArguments]]: values to put in front of the values each call passes.

When you call it, it puts the saved values first, then calls the wrapped function with the saved this.

bind saves a this and an itemPop out in the code editor (opens in a new tab)JavaScript
function show(item) { return this.user + ": " + item; }
const forAsha = show.bind({ user: "Asha" }, "tea");
console.log(forAsha.call({ user: "Ravi" }));

Line 1 makes show, which gives back this.user and the item. Line 2 uses bind to save { user: "Asha" } as this and "tea" as the first value. Line 3 tries to pass Ravi as this with .call(), but it prints Asha: tea. The saved this always wins.

Here are three lines from the spec's steps for using new on a bound function. In these lines, func is the bound function, target is the function it wraps, boundArgs are the saved values, and argList are the values passed now.

How new works on a bound function, three lines from the specText
"Let args be the list-concatenation of boundArgs and argList."
"If SameValue(func, newTarget) is true, set newTarget to target."
"Return ? Construct(target, args, newTarget)."

In plain words, line by line:

  1. Make one list of values: the saved ones first, then the ones passed now.
  2. If newTarget is the bound function itself, use the wrapped function as newTarget instead.
  3. Run new on the wrapped function with that list and newTarget. If that fails, stop and throw.

The saved this is not used here at all: new makes its own object. The spec's bound function steps give a bound function a [[Construct]] step only if the wrapped function has one. These steps are for new. A plain call, like the one above, uses different steps.

A bound constructor still works with newPop out in the code editor (opens in a new tab)JavaScript
function Order(item) { this.item = item; }
const TeaOrder = Order.bind({ item: "ignored" }, "tea");
const order = new TeaOrder();
console.log(order.item, order instanceof Order);

Line 1 makes Order. Line 2 binds it, saving a this that will be ignored and the value "tea". Line 3 calls new TeaOrder(). Line 4 prints tea true:

  • tea, because the saved value was put first in the list.
  • true, because the new object gets its prototype from Order.prototype.

TeaOrder itself has no prototype property of its own, yet new still works.

bind can't make an arrow work with newPop out in the code editor (opens in a new tab)JavaScript
const makeOrder = (item) => ({ item });
const TeaOrder = makeOrder.bind(null, "tea");
try { new TeaOrder(); } catch (error) { console.log(error.name); }

Line 1 makes an arrow. Line 2 binds the first value, "tea", to it. Line 3 tries new TeaOrder(), catches the error, and prints TypeError. bind can't add a [[Construct]] step that the arrow never had. So checking for a prototype property is not a safe way to tell whether new will work: neither bound function has one, but only one works.

Catching calls with Proxy, passing them on with Reflect

A Proxy is an object that stands in front of another object, called its target. A handler object tells the proxy what to do. Each function in the handler is called a trap, because it catches one kind of action. Two traps matter here:

  • The apply trap catches a plain call. It gets the target, the this of the call, and the list of values passed.
  • The construct trap catches new. It gets the target, the list of values, and newTarget.

A proxy can only be called if its target can be called. It only works with new if its target does.

An apply trap changes a greetingPop out in the code editor (opens in a new tab)JavaScript
function greet(user) { return "Hi, " + user; }
const traced = new Proxy(greet, {
  apply(target, thisArg, args) {
    return Reflect.apply(target, thisArg, args).toUpperCase();
  },
});
console.log(traced("Asha"));

Line 1 makes greet. Line 2 makes a proxy called traced in front of it. Line 3 is the apply trap, which runs on every plain call. Line 4 passes the call on to greet with Reflect.apply, then turns the answer into capital letters. Line 7 calls the proxy and prints HI, ASHA. The trap passes on the same values and the same this. It only changes the answer.

Here are three lines from the spec's steps for a proxy. handler is the handler object, and newObj is the object that the construct trap gives back.

How a proxy finds its traps, three lines from the specText
"Let trap be ? GetMethod(handler, "apply")."
"Let trap be ? GetMethod(handler, "construct")."
"If newObj is not an Object, throw a TypeError exception."

In plain words, line by line:

  1. For a plain call, look for an apply function in the handler, and call it trap.
  2. For new, look for a construct function in the handler, and call it trap.
  3. If the construct trap gave back something that is not an object, throw a TypeError.

The lines come from the spec's proxy steps. The apply trap runs for the proxy's [[Call]]. The construct trap runs for its [[Construct]]. If the handler has no such trap, the proxy passes the action straight to the target. A proxy that has been switched off with Proxy.revocable throws an error instead.

A construct trap passes newTarget onPop out in the code editor (opens in a new tab)JavaScript
function Order(item) { this.item = item; }
const traced = new Proxy(Order, {
  construct(target, args, newTarget) {
    return Reflect.construct(target, args, newTarget);
  },
});
console.log(new traced("tea").item);

Line 1 makes Order. Line 2 makes a proxy in front of it. Line 3 is the construct trap, which catches new. Line 4 passes the values and newTarget on with Reflect.construct. Line 7 calls new traced("tea") and prints tea. The trap doesn't make the object itself. Reflect.construct does that job.

A construct trap that gives back a number fails on purposePop out in the code editor (opens in a new tab)JavaScript
const Order = new Proxy(function () {}, {
  construct() { return 3; }
});
new Order();

Line 1 makes a proxy in front of an empty function, which works with new. Line 2 is a construct trap that gives back the number 3. Line 4 calls new Order() and throws a TypeError, because 3 is not an object. Only the error type matters here; each browser words the message differently.

Reflect.apply and Reflect.construct

Reflect is a built-in object with tools that do what JavaScript does on its own:

  • Reflect.apply(fn, thisValue, values) calls fn with the this you choose and a list of values.
  • Reflect.construct(fn, values, newTarget) works like new. The last part is optional and picks a different newTarget.

These are real tools your code can use. Even so, [[Call]] and [[Construct]] stay hidden.

Call a function with a this you choosePop out in the code editor (opens in a new tab)JavaScript
function show(item) { return this.user + ": " + item; }
console.log(Reflect.apply(show, { user: "Asha" }, ["tea"]));

Line 1 makes show, which gives back this.user and the item. Line 2 calls it with { user: "Asha" } as this and the list ["tea"]. It prints Asha: tea. Compare it with the earlier Reflect.construct(Order, ["tea"], SpecialOrder). That one picked the new object's prototype. This one picks this for a plain call.

Calls in a checkout page

Picture a checkout page with a price and a small fee. A method reads the price from its object. Then it passes that price to a plain function that adds the fee. You never write [[Call]] yourself. But knowing where this comes from, and where a parameter comes from, makes bugs easier to find.

A checkout totalPop out in the code editor (opens in a new tab)JavaScript
function showTotal(price) { return price + 2; }
const checkout = { price: 3, show() { return showTotal(this.price); } };
console.log(checkout.show());

Line 1 makes showTotal, which adds 2 to a price. Line 2 makes checkout with a price of 3 and a method, show. The method passes this.price to showTotal. Line 3 calls checkout.show() and prints 5. In that call:

  • this is checkout, because the call has checkout. before the method name.
  • showTotal's parameter price is 3, because show passed it in.

Be careful when you hand checkout.show to other code, for example as a click handler. The other code calls it alone, without checkout. in front, so this is lost. To keep checkout as this, do one of these:

  • Pass an arrow that makes the call: () => checkout.show().
  • Pass a bound copy: checkout.show.bind(checkout).

You don't need a Proxy for this. Use a Proxy only when you really need to catch calls.

What can each function do?
  • An arrow such as item => item
  • The short method cart.show
  • A function made with function Order(item) {}
  • Order.bind(null, "tea")
  • A class Order
  • A class GiftOrder extends Order
Try it yourself
0 of 6 correct

Put each function in the group that says what works with it. Think about [[Call]] and [[Construct]], not typeof.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

A class goes in the third group. It does have a [[Call]] step, but that step always throws, so only new works. The groups say what works, not which steps exist. The bound Order is a surprise the other way: it has no prototype property of its own, but new still works.

Easy mistakes to avoid

Something can look like a function and still not work in every way. First ask what the function can do. Then ask what this line tries to do with it: a plain call, or new. A property like prototype can be a hint, but it doesn't tell you for sure.

A short method can be called, but it has no prototypePop out in the code editor (opens in a new tab)JavaScript
const cart = { show() { return "tea"; } };
console.log(cart.show());
console.log(Object.hasOwn(cart.show, "prototype"));

Line 1 makes a cart with a short method, show. Line 2 calls it and prints tea. Line 3 prints false: show has no prototype property of its own. That fits, because a short method has no [[Construct]] step. But the bound Order above had no prototype property either, and new worked on it. So this check is not a sure test.

  • "Every function works with new." Arrows and short methods can be called, but new on them throws.
  • "A class has no [[Call]]." It has one. That step throws a TypeError when you call the class without new.
  • "No prototype property means new will fail." A bound function has none, but new works if the function it wraps works with new.
  • "Hoisting runs the assignment early." A var name holds undefined until its own line runs.
  • "A Proxy can make anything callable." A proxy can be called only if its target can be called.

The table below puts four ideas side by side. Read each row as: "this idea means this, but watch out for that."

Four ideas that are easy to mix up
IdeaWhat it meansWatch out for
Can be calledHas a [[Call]] stepIt may have no [[Construct]] step. Arrows and short methods don't.
Works with newHas a [[Construct]] stepA class has a [[Call]] step too, but calling it without new throws.
prototype propertyFor a normal constructor, it gives the new object its prototype.Having none doesn't prove new will fail. A bound constructor has none.
new.targetThe constructor that new was used with.It is not always the function whose body is running.

When something goes wrong, check these:

  • If new fails, check what kind of function it is: an arrow, a short method, or a normal function.
  • If a new object has the wrong prototype, check the newTarget passed to Reflect.construct or a construct trap.
  • If a method reads the wrong property, check which this the call really passed.

Practice exercises

Read each program first and guess what it prints. Then run it and type the output. The exercises start with one plain call. Then they move on to names set up before the body, new, and a small checkout page. Open the hints one at a time. The worked solution shows the code and explains the result.

Exercise 1 · Warm-upGuess what a plain call prints

A checkout helper adds a small fee to a price. Read the call at the bottom, then follow the return line. What number shows up in the console?

Starter codePop out in the code editor (opens in a new tab)JavaScript
function addFee(price) {
  return price + 2;
}
console.log(addFee(3));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upGuess what is ready before the body runs

    A receipt helper calls label before the line that makes it. It also reads fee before the line that sets it. Type the whole line it prints. Why does one name work, while the other still holds undefined?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function receipt(item) {
      console.log(label(item), fee);
      var fee = 2;
      function label(value) { return "Item: " + value; }
    }
    receipt("tea");

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeCheck this in strict mode

      Some code needs to know what this is when a function is called on its own. Run the strict mode example and type the true or false it prints. Which of the three call steps decides the value of this?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      function strictThis() {
        "use strict";
        return this;
      }
      console.log(strictThis() === undefined);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFollow the object new makes

        Picture an order card made for tea. Follow new Order. Which object does line 2 change? What does the last line print?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        function Order(item) {
          this.item = item;
        }
        console.log(new Order("tea").item);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeUse new on a bound Order

          A page picks tea before it makes an order. Guess both values the program prints. Does the saved this object become the new object?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          function Order(item) { this.item = item; }
          const TeaOrder = Order.bind({ item: "ignored" }, "tea");
          const order = new TeaOrder();
          console.log(order.item, order instanceof Order);

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeFollow the calls on a checkout page

            Your checkout page shows the final price from a method. First find this in the method call. Then find the value passed to showTotal. What number will the customer see in the console?

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            function showTotal(price) { return price + 2; }
            const checkout = { price: 3, show() { return showTotal(this.price); } };
            console.log(checkout.show());

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, first decide: is this a plain call, or a call with new? Then work out the parameters and this before you read the body. For questions about classes and proxies, ask two things. What can the function do? And what does this line try to do with it?

              Function calls in the spec quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Which hidden step starts a plain function call?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this plain call print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                function addFee(price) { return price + 2; }
                console.log(addFee(3));

                Choose an answer to see the explanation.

              3. Question 3 of 8When does a call set up its names?

                Choose an answer to see the explanation.

              4. Question 4 of 8What does this hoisting example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                function receipt() { console.log(fee); var fee = 2; }
                receipt();

                Choose an answer to see the explanation.

              5. Question 5 of 8What does this new Order example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                function Order() { this.item = "tea"; }
                console.log(new Order().item);

                Choose an answer to see the explanation.

              6. Question 6 of 8What happens when a derived class uses this before super()?

                Choose an answer to see the explanation.

              7. Question 7 of 8What does a bound copy of Order keep?

                Choose an answer to see the explanation.

              8. Question 8 of 8What must a Proxy construct trap give back?

                Choose an answer to see the explanation.

              A wrong answer helps you find the exact step you missed. For example, a var name that holds undefined is not the same as a let name that can't be read yet. And a class that throws when called is not the same as a function with no [[Call]] step.

              Key takeaways

              A call is easier to follow when you split it into two parts: the setup, and then the body. [[Call]] or [[Construct]] picks the way. The setup gives the call its names. Then the body runs with those values. A bound function or a proxy can pass a call on, but it can't give the wrapped function a step it doesn't have.

              • [[Call]] makes a new context, picks this by the function's [[ThisMode]], then runs the body.
              • Before the body runs, FunctionDeclarationInstantiation sets up the parameters, inner functions, var, let, and const names.
              • [[Construct]] gets a newTarget. A base constructor makes the new object before its body runs.
              • A derived class must call super() before it uses this. A class can't be called without new.
              • Arrows and short methods have no [[Construct]]. A bound function works with new only if the function it wraps does.
              • A proxy's apply trap catches plain calls, and its construct trap catches new. Reflect passes each one on.

              Remember the one-liner.
              [[Call]] runs a function; [[Construct]] makes a new object, with a newTarget.

              Coming next: Internal methods & exotic objects. It uses the same kind of hidden steps to explain how objects read and write properties, and how some special objects work. Go back to execution contexts any time the setup of a call feels new.

              CompleteFrontend Clear concepts. Working examples.