Javascript function call with arguments

JavaScript Function Parameters

A JavaScript function does not perform any checking on parameter values (arguments).

Function Parameters and Arguments

Earlier in this tutorial, you learned that functions can have parameters:

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.

Default Parameters

If a function is called with missing arguments (less than declared), the missing values are set to undefined .

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

Example

Default Parameter Values

ES6 allows function parameters to have default values.

Example

If y is not passed or undefined, then y = 10.

Function Rest Parameter

The rest parameter (. ) allows a function to treat an indefinite number of arguments as an array:

Example

function sum(. args) <
let sum = 0;
for (let arg of args) sum += arg;
return sum;
>

let x = sum(4, 9, 16, 25, 29, 100, 66, 77);

The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Example

x = findMax(1, 123, 500, 115, 44, 88);

function findMax() let max = -Infinity;
for (let i = 0; i < arguments.length; i++) if (arguments[i] > max) max = arguments[i];
>
>
return max;
>

Or create a function to sum all input values:

Example

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() let sum = 0;
for (let i = 0; i < arguments.length; i++) sum += arguments[i];
>
return sum;
>

If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object.

Arguments are Passed by Value

The parameters, in a function call, are the function’s arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument’s locations.

If a function changes an argument’s value, it does not change the parameter’s original value.

Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function.

Источник

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.

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.

Источник

Читайте также:  Python read png file
Оцените статью