Get calling function in javascript

Function.prototype.call()

The call() method calls the function with a given this value and arguments provided individually.

Try it

Syntax

call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN) 

Parameters

The value to use as this when calling func . If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

Arguments for the function.

Return value

The result of calling the function with the specified this value and arguments.

Description

Note: This function is almost identical to apply() , except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array — for example, func.call(this, «eat», «bananas») vs. func.apply(this, [«eat», «bananas»]) .

Normally, when calling a function, the value of this inside the function is the object that the function was accessed on. With call() , you can assign an arbitrary value as this when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.

Читайте также:  Idea настроить версию java

Warning: Do not use call() to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means new.target is undefined , and classes throw an error because they can’t be called without new . Use Reflect.construct() or extends instead.

Examples

Using call() to invoke a function and specifying the this value

In the example below, when we call greet , the value of this will be bound to object obj , even when greet is not a method of obj .

function greet()  console.log(this.animal, "typically sleep between", this.sleepDuration); > const obj =  animal: "cats", sleepDuration: "12 and 16 hours", >; greet.call(obj); // cats typically sleep between 12 and 16 hours 

Using call() to invoke a function without specifying the first argument

If the first thisArg parameter is omitted, it defaults to undefined . In non-strict mode, the this value is then substituted with globalThis (which is akin to the global object).

.globProp = "Wisen"; function display()  console.log(`globProp value is $this.globProp>`); > display.call(); // Logs "globProp value is Wisen" 

In strict mode, the value of this is not substituted, so it stays as undefined .

"use strict"; globalThis.globProp = "Wisen"; function display()  console.log(`globProp value is $this.globProp>`); > display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined 

Transforming methods to utility functions

call() is almost equivalent to a normal function call, except that this is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling array.map(callback) , you use map(array, callback) , which avoids mutating Array.prototype , and allows you to use map with array-like objects that are not arrays (for example, arguments ).

Take Array.prototype.slice() , for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

const slice = Array.prototype.slice; // . slice.call(arguments); 

Note that you can’t save slice.call and call it as a plain function, because the call() method also reads its this value, which is the function it should call. In this case, you can use bind() to bind the value of this for call() . In the following piece of code, slice() is a bound version of Function.prototype.call() , with the this value bound to Array.prototype.slice() . This means that additional call() calls can be eliminated:

// Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // . slice(arguments); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 1, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Function.prototype.caller

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: In strict mode, accessing caller of a function throws an error — the API is removed with no replacement. This is to prevent code from being able to «walk the stack», which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read the rationale for the deprecation of arguments.callee .

The caller accessor property of Function instances returns the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError .

Description

If the function f was invoked by the top-level code, the value of f.caller is null ; otherwise it’s the function that called f . If the function that called f is a strict mode function, the value of f.caller is also null .

Note that the only behavior specified by the ECMAScript specification is that Function.prototype has an initial caller accessor that unconditionally throws a TypeError for any get or set request (known as a «poison pill accessor»), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the caller property, if it’s anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill Function.prototype.caller accessor to specially handle this values that are non-strict functions.

(function f()  if (Object.hasOwn(f, "caller"))  console.log( "caller is an own property with descriptor", Object.getOwnPropertyDescriptor(f, "caller"), ); > else  console.log( "f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller", ); console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(f), "caller", ).get.call(f), ); > >)(); // In Chrome: // caller is an own property with descriptor // In Firefox: // f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller // null 

This property replaces the obsolete arguments.caller property of the arguments object.

The special property __caller__ , which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.

Examples

Checking the value of a function’s caller property

The following code checks the value a function’s caller property.

function myFunc()  if (myFunc.caller === null)  return "The function was called from the top!"; > else  return `This function's caller was $myFunc.caller>`; > > 

Reconstructing the stack and recursion

Note that in case of recursion, you can’t reconstruct the call stack using this property. Consider:

function f(n)  g(n - 1); > function g(n)  if (n > 0)  f(n); > else  stop(); > > f(2); 

At the moment stop() is called the call stack will be:

so if you tried to get the stack trace in the stop() function like this:

let f = stop; let stack = "Stack trace:"; while (f)  stack += `\n$f.name>`; f = f.caller; > 

the loop would never stop.

Strict mode caller

If the caller is a strict mode function, the value of caller is null .

function callerFunc()  calleeFunc(); > function strictCallerFunc()  "use strict"; calleeFunc(); > function calleeFunc()  console.log(calleeFunc.caller); > (function ()  callerFunc(); >)(); // Logs [Function: callerFunc] (function ()  strictCallerFunc(); >)(); // Logs null 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript Function call()

With the call() method, you can write a method that can be used on different objects.

All Functions are Methods

In JavaScript all functions are object methods.

If a function is not a method of a JavaScript object, it is a function of the global object (see previous chapter).

The example below creates an object with 3 properties, firstName, lastName, fullName.

Example

const person = <
firstName:»John»,
lastName: «Doe»,
fullName: function () <
return this.firstName + » » + this.lastName;
>
>

// This will return «John Doe»:
person.fullName();

In the example above, this refers to the person object.

this.firstName means the firstName property of this.

this.firstName means the firstName property of person.

What is this?

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined .
In an event, this refers to the element that received the event.
Methods like call() , apply() , and bind() can refer this to any object.

Note

See Also:

The JavaScript call() Method

The call() method is a predefined JavaScript method.

It can be used to invoke (call) a method with an owner object as an argument (parameter).

With call() , an object can use a method belonging to another object.

This example calls the fullName method of person, using it on person1:

Example

const person = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person1 = <
firstName:»John»,
lastName: «Doe»
>
const person2 = <
firstName:»Mary»,
lastName: «Doe»
>

// This will return «John Doe»:
person.fullName.call(person1);

This example calls the fullName method of person, using it on person2:

Example

const person = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person1 = <
firstName:»John»,
lastName: «Doe»
>
const person2 = <
firstName:»Mary»,
lastName: «Doe»
>

// This will return «Mary Doe»
person.fullName.call(person2);

The call() Method with Arguments

The call() method can accept arguments:

Example

const person = <
fullName: function(city, country) <
return this.firstName + » » + this.lastName + «,» + city + «,» + country;
>
>

const person1 = firstName:»John»,
lastName: «Doe»
>

person.fullName.call(person1, «Oslo», «Norway»);

Источник

Оцените статью