Javascript create function and call it

Function() constructor

The Function() constructor creates Function objects. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval() . However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

Try it

Syntax

new Function(functionBody) new Function(arg0, functionBody) new Function(arg0, arg1, functionBody) new Function(arg0, arg1, /* … ,*/ argN, functionBody) Function(functionBody) Function(arg0, functionBody) Function(arg0, arg1, functionBody) Function(arg0, arg1, /* … ,*/ argN, functionBody) 

Note: Function() can be called with or without new . Both create a new Function instance.

Parameters

Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript parameter (any of plain identifier, rest parameter, or destructured parameter, optionally with a default), or a list of such strings separated with commas.

As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: «x», «theValue = 42», «[a, b] /* numbers */» — or «x, theValue = 42, [a, b] /* numbers */» . ( «x, theValue = 42», «[a, b]» is also correct, though very confusing to read.)

Читайте также:  Window programming in java

A string containing the JavaScript statements comprising the function definition.

Description

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than creating a function with a function expression or function declaration and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion:

`function anonymous($args.join(",")> )  $functionBody> >`; 

This is observable by calling the function’s toString() method.

However, unlike normal function expressions, the name anonymous is not added to the functionBody ‘s scope, since functionBody only has access the global scope. If functionBody is not in strict mode (the body itself needs to have the «use strict» directive since it doesn’t inherit the strictness from the context), you may use arguments.callee to refer to the function itself. Alternatively, you can define the recursive part as an inner function:

const recursiveFn = new Function( "count", ` (function recursiveFn(count) < if (count < 0) < return; >console.log(count); recursiveFn(count - 1); >)(count); `, ); 

Note that the two dynamic parts of the assembled source — the parameters list args.join(«,») and functionBody — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts.

new Function("/*", "*/) ); // SyntaxError: Unexpected end of arg string // Doesn't become "function anonymous(/*) <*/) <>" 

Examples

Specifying arguments with the Function constructor

The following code creates a Function object that takes two arguments.

// Example can be run directly in your JavaScript console // Create a function that takes two arguments, and returns the sum of those arguments const adder = new Function("a", "b", "return a + b"); // Call the function adder(2, 6); // 8 

The arguments a and b are formal argument names that are used in the function body, return a + b .

Creating a function object from a function declaration or function expression

// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name // Observe that new Function is called. This is so we can call the function we created directly afterwards const sumOfArray = new Function( "const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray", )(); // call the function sumOfArray([1, 2, 3, 4]); // 10 // If you don't call new Function at the point of creation, you can use the Function.call() method to call it const findLargestNumber = new Function( "function findLargestNumber (arr) < return Math.max(. arr) >; return findLargestNumber", ); // call the function findLargestNumber.call(>).call(>, [2, 4, 1, 8, 5]); // 8 // Function declarations do not require a return statement const sayHello = new Function( "return function (name) < return `Hello, $` >", )(); // call the function sayHello("world"); // Hello, world 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Function

The Function object provides methods for functions. In JavaScript, every function is actually a Function object.

Constructor

Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval() . However, unlike eval() , the Function constructor creates functions that execute in the global scope only.

Instance properties

These properties are defined on Function.prototype and shared by all Function instances.

Represents the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError . Use the arguments object inside function closures instead.

Represents the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError .

The constructor function that created the instance object. For Function instances, the initial value is the Function constructor.

These properties are own properties of each Function instance.

The display name of the function.

Specifies the number of arguments expected by the function.

Used when the function is used as a constructor with the new operator. It will become the new object’s prototype.

Instance methods

Calls a function with a given this value and optional arguments provided as an array (or an array-like object).

Creates a new function that, when called, has its this keyword set to a provided value, optionally with a given sequence of arguments preceding any provided when the new function is called.

Calls a function with a given this value and optional arguments.

Returns a string representing the source code of the function. Overrides the Object.prototype.toString method.

Specifies the default procedure for determining if a constructor function recognizes an object as one of the constructor’s instances. Called by the instanceof operator.

Examples

Difference between Function constructor and function declaration

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using eval() with code for a function expression.

// Create a global property with `var` var x = 10; function createFunction1()  const x = 20; return new Function("return x;"); // this `x` refers to global `x` > function createFunction2()  const x = 20; function f()  return x; // this `x` refers to the local `x` above > return f; > const f1 = createFunction1(); console.log(f1()); // 10 const f2 = createFunction2(); console.log(f2()); // 20 

While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

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 18, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when «something» invokes it (calls it).

Example

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:
(parameter1, parameter2, . )

The code to be executed, by the function, is placed inside curly brackets: <>

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when «something» invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will «return» to execute the code after the invoking statement.

Functions often compute a return value. The return value is «returned» back to the «caller»:

Example

Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x
let x = myFunction(4, 3);

function myFunction(a, b) // Function returns the product of a and b
return a * b;
>

Why Functions?

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

The () Operator

The () operator invokes (calls) the function:

Example

Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>

Accessing a function with incorrect parameters can return an incorrect answer:

Example

function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>

Accessing a function without () returns the function and not the function result:

Example

function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>

Note

As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Example

Instead of using a variable to store the return value of a function:

You can use the function directly, as a variable value:

You will learn a lot more about functions later in this tutorial.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Example

// code here can NOT use carName

function myFunction() let carName = «Volvo»;
// code here CAN use carName
>

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Источник

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