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 'antd' 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('show'); } //第二种 //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('newshow'); } } 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
$.get(‘’,{},function(data){ }) var test=function(callback){ callback.apply(this,arguments) }
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; } } }
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 'react'; const simpleHoc = WrappedComponent => { console.log('simpleHoc'); 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!