search
HomeWeb Front-endJS TutorialHow to define javascript function? Common usage of js functions

What this article brings to you is how to define javascript functions? The common usage of js functions has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We know that there are many ways to write js functions, function declarations, function expressions, Function-style constructors, self-executing functions, including Es6 arrow functions, Class class writing methods, High-level Function, function throttling/function anti-shake, below I will start to talk about the most basic usage of the above types.

Function declarative writing method

This writing method is the most basic writing method. Use the keyword function to define the function. After the function is declared It will not be executed immediately, it will be called when we need it. This function is global. If there are two declarative functions with the same name, the second one will overwrite the first one.

   function   Test(){
    } 

There is an interview question as follows, asking for output:

function  test1(){
 alert('test1')  
} ;
test1() ;  
function  test1(){
 alert('test2')  
} ;

The answer is: 'test2'

How to write function expressions

Define a variable pointing to a function, which can actually be regarded as an anonymous function. This kind of function can only be called after it is declared. If it is called before it is declared, an error will be reported.

      var   test=function(){
     }

There is an interview question as follows, asking for output:

var test=function(){ alert('test1')  } ;
test() ; 
var test=function(){ alert('test2')  } ;

The answer is: test1

Function-style constructor

Through JavaScript function constructor (Function ()) instantiation to define a function, first define various variables, and finally define the return value or output of the function. This kind of function is not commonly used.

var test= new Function("a", "b", "return a * b");
test();

Self-executing function

This kind of function has no name, only a declaration body, and is actually an anonymous self-calling function. The advantage of this kind of function is to keep the variables independent and not polluted by external variables, forming a closed function execution environment.

The writing method is as follows:

(function(){

})();
这种写法比较常见,比如Jquery框架里面就用到这种写法:
‘use strict’;

;(function(context,win){
})(Jquery||undefined,window)

There are also writing methods like closures. We often encounter the writing methods of interview questions similar to the following:

var ps=tr.getElementsByTagName("p");
for(var  i=0;i<ps.length;i++){
     (function(p){
      p.onclick=function(){
      alert(this.innerHTML);
      }
})(ps[i])
}

Arrow function

This declaration method is introduced in Es6. The arrow function is a shorthand function expression, and its internal this does not point to itself, but to the top-level object of the current execution environment (such as window, react The component points to the class parent component of the current component), and arrow functions are always anonymous. The writing method is as follows:

const   test=()=>{
}

For example, this in the following function points to window

const  test={
       array:[1,2],
       show:()=>{
            console.log(this. array)
      }
}
test.show();//undefined

, and this in onSearch of the react component below points to the Test component, and the Test component can be found through this The functions or state and props defined below. Note that the code commented in the constructor is to point this of onSearch to the Test component. It is written differently from the arrow function, but has the same effect.

		import  {Button}  from &#39;antd&#39;
			class Test extends Component {
				constructor(props) {
					super(props);
                  //this.onSearch = this.onSearch.bind(this)
				}
				//onSearch(){
						console.log(this);
				//}
				onSearch=()=>{
					console.log(this);
				}
				render() {
					return ( < p >
						<Button onClick={this.onSearch}>测试</Button>
						< /p>
					)
				}
			}

ClassClass writing method

Js did not have the concept of classes before. Before, some attributes were mounted on the instance of the function. Or implement the concept of function-based classes through prototypes. For example, the following writing method

function  Test (){

this.name=’’;

//this.show=function(){

//}

}

Test.prototype.show=function(){

   Console.log(this.name)

}

new Test().show();

ES6 introduces the concept of Class as a template for objects. Classes can be defined through the class keyword. Basically, the ES6 class can be regarded as just a syntactic sugar. Most of its functions can be achieved by ES5. The new class writing method only makes the writing of object prototypes clearer and more like the syntax of object-oriented programming.

Basic writing method:

class   test {
//第一种
Show() {
alert(&#39;show&#39;);
}
//第二种
//Show=()=>{
//}
}
var test1 = new test();
var  test2= new test();

Note that the two methods in this class are written differently

The first declared method will point to the prototype prototype of test

test1. Show=== test2.Show//true

The second declared method will point to the instance of test, and a Show method will be generated for each instantiation.

test1. Show=== test2.Show//false

The inheritance is written as follows, so that newTest will inherit Show in test

class    newTest  extends   test{
   Show() {
       super. Show();
       alert(&#39;newshow&#39;);
   }
}
 var  test=new  newTest  ();
 test. Show()

If there is no Show declared in newTest method, the Show method in the parent class test will be called. If declared, the Show method of newTest will be called. The child calls the parent's method using the super keyword to access it, such as

super. Show();

  • ##Higher-order function

Higher-order function is called Higher-order function in English. JavaScript functions actually point to a variable. Since variables can point to functions and function parameters can receive variables, a function can receive another function as a parameter. This function is called a higher-order function. To put it simply, "a higher-order function is a function that can take a function as a parameter or a function as a return value." In fact, the most typical application is the callback function.

High-order functions generally have the following scenarios

1. Function callback

$.get(‘’,{},function(data){

})

var   test=function(callback){
        callback.apply(this,arguments)

}

2 Function currying

First fill in a few functions in a function The technology of parameterizing (and then returning a new function) is called Currying. This definition may be a bit difficult to understand. Let’s first look at the implementation of a simple function currying:

      var currency=function(fn){                      
      var self=this;                      
      var arr=[];                      
      return function(){                            
      if(arguments.length==0){                                  
      return  fn.apply(this,arr  );
   }else{
[].push.apply(arr,arguments);                                  
return arguments.callee;
}   
}
}

and then Take a look at the call:

var  sum=function(){
                      var total=0;
                       var  argArr=arguments;
                       for (var i = 0; i < argArr.length; i++) {
                                  total+=argArr[i];
                       }   
                        return  total;
 }       
var test=  currency(sum);           
test(100,200);
test(300)
alert(test());

其实简单的解释就是currency函数里面定义一个局部变量arr数组,然后返回一个函数,返回的函数体里对变量arr进行了赋值,每次当函数传入参数的时候都会将参数push到arr里面,然后返回函数体,形成了一个闭包。当没有参数传入的时候就直接执行传入的sum函数,然后执行函数sum传入的的参数就是arr.

3.函数扩展

函数扩展一般是通过原型来扩展,传入一个回调函数,比如给Array扩展一个函数Filter代码如下:

Array.prototype.Filter=function(callback){
    …..
}

做过react 开发的都知道有高阶组件的概念,其实高阶组件是通过高阶函数演变的,只不过传入的参数是组件,然后返回值是一个组件,来看下面的一段代码  

export default simpleHoc(Usual);
import React, { Component } from &#39;react&#39;;
 
const simpleHoc = WrappedComponent => {
  console.log(&#39;simpleHoc&#39;);
  return class extends Component {
    render() {
      return <WrappedComponent {...this.props}/>
    }
  }
}
export default simpleHoc;

函数节流/函数防抖

一般做前端时间比较长的人对这个概念比较熟了,但是刚接触的人估计会有点懵逼。

这两个概念都是优化高频率执行js代码的一种手段,来看下他们的基本概念

函数节流:函数在设定的时间间隔内最多执行一次

应用场景:高频率点击事件

var  isEnable=true;

document.getElementById("testSubmit").onclick=function(){  
if(!isEnable){           
return;
  }
  isEnable=false;
  setTimeout(function(){
        console.log("函数节流测试");
        isEnable = true;
  }, 500);
}

函数防抖:函数在一段时间内不再被调用的时候执行

应用场景:onresize onscroll事件,oninput事件

Var  timer=null;
Window. onscroll=function(){
     clearTimeout(timer);
     timer = setTimeout(function(){
     console.log("函数防抖测试");
    }, 500);
}

从上面两个事件可以看出来区别:

函数节流在第一次操作之后的500毫秒内再次点击就只执行一次,不会重置定时器,不会重新计时

函数防抖是在持续触发onscroll事件的时候会重置重置定时器,重新计时,直到不触发事件的500毫秒之后执行一次

The above is the detailed content of How to define javascript function? Common usage of js functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment