Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Function object in JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to use Function objects in JavaScript". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use Function objects in JavaScript.

Instance definition

In Js, a function is an instance object of the Fuction class, so we can define a function by instantiation, which fully understands the concept that a function is also an object.

Copy the code

"use strict"; / / Parameter 1: formal parameter, parameter 2: function code body let func = new Function ("title", "console.log (title)"); func ("Mr. Yunya's blog"); Standard definition

Defining functions using the Function class is too cumbersome, so it is recommended to use the function standard syntax for definition.

Copy the code

"use strict"; function func (title) {console.log (title);} func ("Mr. Yunya's blog"); literal object

We can define a function in an object, which is often called an object method.

Copy the code

"use strict"; let obj = {description: "this is an object property", show:function (title) {console.log ("this is an object method, passed in parameters are:", title);},} obj.show ("Cloud Cliff"); anonymous function

Globally declared standard definition functions are stored in the window object, which has many drawbacks.

Because our function name may cause the window method to be missing if it is not appropriate.

Copy the code

"use strict"; function func (title) {console.log (title);} func ("Mr. Yunya's blog"); console.log (window.func); / / Yes

Therefore, anonymous functions can be defined by assignment, declared using let/const before definition, so that it will not be pressed into the window object, and note that it ends with;. Note: anonymous functions declared in var will be pushed into the window object

Copy the code

"use strict"; let func = function (title) {console.log (title);}; func ("Mr. Yunya's blog"); console.log (window.func); / / undefined function execution function promotion

The function defined by the standard will be promoted and can be used first and then defined, which is not in accordance with the specification.

However, anonymous functions do not improve the function.

The promotion of the function comes before the promotion of the var variable, so if the function name repeats the variable defined with var, the name will be obtained by the variable and the function will be treated as garbage collection.

Even if var is used to define an anonymous function, the function will not be promoted, but the function will be pressed into the window object, so it is recommended to use let/const to receive anonymous functions.

The standard declaration function will be promoted

Copy the code

"use strict"; func ("Mr. Yunya's blog"); / / executed function func (title) {console.log (title);} console.log (window.func); / / Yes

Anonymous functions will not be promoted

Copy the code

"use strict"; func ("Mr. Yunya's blog"); / / Uncaught ReferenceError: Cannot access' func' before initialization let func = function (title) {console.log (title);} console.log (window.func); self-executing function

A long time ago, if you wrote a Js module, to prevent global scope contamination, you would put the code into a self-executing function.

But not anymore, because let/const has block scope, and their appearance determines that the modules we write in the future do not have to be encapsulated with self-executing functions.

First, let's take a look at how self-executing functions are used.

Copy the code

"use strict"; (function (title) {console.log (title); / / execute by yourself}) ("Mr. Yunya's blog"); / / call here

Self-executing function encapsulation

Copy the code

(function () {function show () {console.log ("show function performed");} function test () {console.log ("test function performed");} window.module = {show, test};}) ()

Let scope encapsulation

Copy the code

{let show = function () {console.log ("show function performed");} let test = function () {console.log ("test function performed");} window.module = {show, test};}

Call

Copy the code

/ / Note that the module "use strict"; module.show (); module.test (); parameter-dependent parameter arguments should be introduced above.

Formal parameters are parameters set when the function is declared, and arguments refer to the values passed when the function is called. Note that parameters must be passed one by one!

When the number of formal parameters is greater than the actual parameters, the value of the formal parameters without passing parameters is undefined.

When the number of arguments is greater than the number of parameters, more arguments will be ignored and no error will be reported.

Use the function name .length to get the number of formal parameters to be passed

Copy the code

"use strict"; function test (F1, f2, f3) {console.log (F1); / / first console.log (f2); / / second console.log (f3); / / undefined} test ("first", "second"); default parameter

The default parameter is placed at the end, using the value of the default parameter when no argument is passed, and the value passed by the argument when there is an argument.

Copy the code

"use strict"; function test (F1, f2, f3) {f3 = f3 | "default parameter"; / / the way the default parameter is set in the old version console.log (F1); / / the first console.log (f2); / / the second console.log (f3) / / default parameter} test ("first", "second")

Copy the code

"use strict"; / / the new version sets the default parameter function test (F1, f2, f3 = "default parameter") {console.log (F1); / / first console.log (f2); / / second console.log (f3) / / default parameter} test ("first", "second"); function parameters

The function itself can also be passed to another function as an argument.

Copy the code

"use strict"; function F1 (func) {console.log ("F1..."); console.log ("parameters:", func); func ("parameters passed to f2"); / / execute f2} function f2 (y) {console.log ("f2") Console.log ("parameters:", y);} F1 (f2); arguments

When a function wants to receive an infinite number of arguments, it does not specify a formal parameter and uses arguments to receive it (which must be the name).

Note: arguments is an Arguments object, not an array. But we can convert it to an array before we operate.

Copy the code

"use strict"; function show () {console.log (arguments); / / Arguments (6) [callee: (...), Symbol (Symbol.iterator):]} show; Grammar

When a formal parameter wants to receive an infinite number of parameters, it can be added before the formal parameter name. The parameter receives an infinite number of parameters as an Array object.

This is a more recommended way to use

Copy the code

"use strict"; function show (... args) {console.log (args); / / (6) [1 show 2 args 3 4 5 5 6]} show

When the argument is the data type of an array or class array, you can use. Grammar to pass parameters one by one for formal parameters. Note, however, that this is not allowed in strict mode.

Copy the code

/ / "use strict"; you can't do this in strict mode function show (f1rect f2rec f3rect f4je f5) {console.log (f1); / / 1 console.log (f2); / / 2 console.log (f3); / / 3 console.log (f4); / / 4 console.log (f5) / / 5} show (. [1, 2, 3, 4, 5, 6]); arrow function

The arrow function is an abbreviated form of function declaration, and it is not recommended when using recursive calls, constructors, and event handlers.

You can use an empty extension when there is no parameter, and the code block is too short to omit curly braces.

When the function body is a single expression, there is no need for return return processing, the system will automatically return the result of the expression evaluation.

Multi-parameter passing is separated by commas like ordinary declaration functions

Parameter parentheses can be omitted when there is only one parameter.

You can use an empty extension when there is no parameter, and the code block is too short to omit curly braces.

Copy the code

"use strict"; let show = () = > console.log ("executed"); show ()

When the function body is a single expression, there is no need for return return processing, the system will automatically return the result of the expression evaluation.

Copy the code

"use strict"; let show = () = > "you are so handsome"; const res = show (); console.log (res); / / you are so handsome

Multi-parameter passing is separated by commas like ordinary declaration functions

Copy the code

"use strict"; let show = (F1, f2, f3) = > {console.log (F1); console.log (f2); console.log (f3);}; / / add semicolon show ("first", "second", "third")

Parameter parentheses can be omitted when there is only one parameter.

Copy the code

"use strict"; let show = F1 = > console.log (F1); show ("first") / / first recursive call

Recursion refers to the way in which a function invokes itself.

Mainly used for loop operations with uncertain quantity

There must be an opportunity to quit, or you will fall into an endless cycle.

The following example shows the use of recursion for cumulative operations.

Copy the code

"use strict"; function show (num) {if (! num) {return 0;} return num + show (num-1);} let res = show; console.log (res); / / 5050

The following example shows the use of recursive printing of inverted triangles.

Copy the code

"use strict"; function show (num) {if (! num) {return;} console.log ("*" .repeat (num)); show (num-1);} show (5); callback function

Callback functions refer to functions that will be called by other functions in a particular case, such as mouse events and keyboard events.

Copy the code

"use strict"; / callback function document.querySelector ("div"). AddEventListener ("click", (event) = > console.log (event.target)); / / because the this points to different points, we use event.target to print the label function

When formatting a string using a template literal, you can specify a label function. The first parameter is an array of string values, and the rest are label variables.

Be careful! The label function will be executed automatically!

Copy the code

"use strict"; function show (str,... args) {console.log (str); / / (3) ["name is:", "↵ age is:", "raw: Array (3)] console.log (args); / / (2) [" Cloud Cliff ", 18]} let username =" Cloud Cliff " Let age = 18; let str = show` name: ${username}\ nAge: ${age} `. Now that you have a better understanding of "how to use Function objects in JavaScript", you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report