Home > Web Front-end > JS Tutorial > body text

How to define javascript function? Common usage of js functions

不言
Release: 2018-10-13 15:02:36
forward
2398 people have browsed it

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(){
    } 
Copy after login

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

function  test1(){
 alert('test1')  
} ;
test1() ;  
function  test1(){
 alert('test2')  
} ;
Copy after login

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(){
     }
Copy after login

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

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

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();
Copy after login

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)
Copy after login

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])
}
Copy after login

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=()=>{
}
Copy after login

For example, this in the following function points to window

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

, 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>
					)
				}
			}
Copy after login

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();
Copy after login

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();
Copy after login

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()
Copy after login

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)

}
Copy after login

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;
}   
}
}
Copy after login

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());
Copy after login

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

3.函数扩展

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

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

做过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;
Copy after login

函数节流/函数防抖

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

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

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

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

var  isEnable=true;

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

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

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

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

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

函数节流在第一次操作之后的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!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!