search
HomeWeb Front-endJS TutorialWhat is the function function of js? How to use function in js

The content of this article is about what is the function of js? The usage of function in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Function and function

Function is a reference type provided by JavaScript, and Function objects are created through the Function type.
In JavaScript, functions also exist in the form of objects, and each function is a Function object.

//字面量方式创建函数
var fun =function () {
    console.log(100)
};
//函数声明方式创建函数
function fn () {
    console.log(200)
};
/*     创建Funtion类型的对象
*       var 函数名 = new Function('参数',''函数体)*/
var f = new Function('a','console.log(a)');
f(2);//以函数方式调用

Function type

Function’s apply() method

Function’s apply() method is used to call a function , and accepts the specified this value and an array as parameters.

//定义函数
function fun(value) {
    console.log(value)
}
/*
函数的apply()方法——>用于调用一个函数
     函数名.apply(thisArg,[argsArray])
       thisArg——>可选项,函数运行时使用的this值
       argsArray——>可选项,一个数组或者类数组对象,其中的元素作为单独的参数传给Function函数。*/
fun.apply(null,['100']);

Function’s call() method

Function’s call() method is used to call a function and accepts the specified this value and parameter list.

var fun  = function (value,a,b,) {
    console.log(value,a,b,)
}
/*
*   call()方法调用函数
*   函数名.call(thisArg,arg1,arg2,…)
*
*   和apply()的区别在于提供参数的方式不同
*/
fun.call(null,2,3,4);//2 3 4

Function’s bind method

Function is used to create a new function, called a bound function, and accepts the specified this value as a parameter, and a parameter list

var fun = function (a,b,c) {
    console.log( a,b,c)
}
/*  bind方法->相当于复制一份当前函数
*   函数名.bind(thisArg,arg1,arg2,...)
*     thisArg->当绑定函数被调用时,该属性作为原函数运行时的this指向
*     arg->参数。当绑定函数被调用时,这些参数将在实参之前传递给被绑定的方法
*     */

var v =fun.bind(null,2,3,4);
v();//2 3 4

No overloading

In other development languages, functions have a feature called overloading. That is to define multiple functions with the same name, but each function receives a different number of parameters. The program will determine which function is called based on the number of actual parameters passed during the call.
There is no overlapping of functions in a single JavaScript. If multiple functions with the same name are defined, only the last defined function is valid.

arguments object

Although there is no overloading, JavaScript provides arguments objects that can simulate the phenomenon of function overloading.

/*
*    argumengs对象
*    *该对象存储当前函数中所有的参数(实参)->类数组对象
*    *该对象一般用于函数中
*    *作用-用于获取当前函数的所有参数
*    *arguments.length->函数所有参数(实参)的个数*/
function fun() {
    var num = arguments.length;
    switch (num){
        case 2://参数个数
            return arguments[0]+arguments[1];
        break;
        case 3:
            return arguments[0]+arguments[1]+arguments[2];
        break;
    }
}
console.log(fun(4,5));//9
console.log(fun(4,5,6));//15

Recursion

A function that calls itself within the function body is called a recursive function. In a sense, recursion is similar to a loop. Both execute the same code repeatedly and both require a termination condition to avoid infinite loops and infinite recursion.
In a function body, if you want to call its own function, there are two ways

  • By using its own function name

  • Passed Use the callee attribute of the arguments object to implement

/*//无线递归
function fun() {
    console.log('23')
    fun()//调用自身函数,实现递归
}
fun()*/

function fn(v) {
    console.log(v);
    if (v>=5){
        return
    }
    /*fn(v+1)*///使用该方法终止递归当执行下列代码输出时,报错
    arguments.callee(v+1)
}
/*fn(0)*/
var f = fn;
fn=null;
f(0);

Special function

Anonymous function

In JavaScript, when the function When used as data, the name does not need to be set. Two uses of anonymous functions

  • You can pass anonymous functions as parameters to other functions.

  • You can define an anonymous function to perform certain one-time tasks.

Callback function

When a function is used as a parameter of another function, the function used as the parameter is called a callback function.

//作为另一个函数参数的函数fun->回调函数
var fun = function () {
    return 2;
};

function fn(v) {
    return v();
}
/*
var result=fn(fun);//函数fun作为函数fn的实参
console.log(result);
*/

//以上代码等同于以下代码
//以下代码中作为参数的函数->匿名回调函数

var f = fn(function(){return 2;});
console.log(f);

Self-tuning function

Self-tuning function is a function that calls itself after defining the function

/*    自调函数->定义即调用的函数
*      相当于在匿名函数外加了小括号
*      第一对括号->定义函数
*      第二对括号->调用函数*/

(function () {
    console.log('23')
})()//23->后边的括号表示调用

One function acts as another function The result is returned, and the function returned as the result is called a function as a value

var one = function(){
    return 100;
}
// 作为值的函数 -> 内部函数的一种特殊用法
function fun(){
    var v = 100;
    // 内部函数
    return function(){
        return v;
    };
}

var result = fun();
// console.log(result);// one函数
// console.log(result());// 100

console.log(fun()());

Closure

Scope chain

Scope chain means that the local scope can access the scope that its parent can access

var a = 10;// 全局变量
function fun(){
    var b = 100;// fun函数作用域的局部变量
    // 内部函数
    function fn(){
        var c = 200;// fn函数作用域的局部变量
        // 内部函数
        function f(){
            var d = 300;// f函数作用域的布局变量
            // 调用变量
            console.log(a);// 10
            console.log(b);// 100
            console.log(c);// 200
            console.log(d);// 300
        }
        f();
        // 调用变量
        // console.log(a);// 10
        // console.log(b);// 100
        // console.log(c);// 200
        // console.log(d);// d is not defined
    }
    fn();
    // 调用变量
    // console.log(a);// 10
    // console.log(b);// 100
    // console.log(c);// c is not defined
    // console.log(d);// d is not defined
}
fun();

Closure

When any internal function is passed When a method is accessed from any outer scope, it is a closure.

var n;// 定义变量,但不初始化值
function fun(){// 函数作用域
    var v = 100;
    // 进行初始化值 -> 一个函数
    n = function(){
        console.log(v);
    }
    // n();
}
fun();

n();// 100

The role of closure

  • Provide shareable local variables

  • Protect shared local variables and provide special reading Write functions of variables

  • Avoid global pollution

Related recommendations:

Introduction to JavaScript Function function types

A brief analysis of the understanding of functions in JS

Function type in ECMAScript_javascript skills

The above is the detailed content of What is the function function of js? How to use function in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)