Home >Web Front-end >JS Tutorial >What are the ways to call functions in javascript
Methods for calling functions in JavaScript: 1. Use the "Object.Function Name()" statement to call; 2. Use "Function Name().call(Caller, Parameter 1, Parameter 2, ... ..);" statement call; 3. Use the "function name().apply(caller, parameter array);" statement call.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
Named functions
<script type="text/javascript"> function show(name){ document.write(name+" hellow") } show('laoli'); </script>
Anonymous function (recommended)
<script type="text/javascript"> var f=function(name){ document.write('name+" hellow") } f('laoli'); </script>
Use the function class to construct an anonymous function
Format: new Function (('Parameter list'), ('Parameter list'), ('Function execution body'));
Note:
<script type="text/javascript"> var f = new Function('name', 'alert(name+"你好");'); f('laoli'); </script>
Column: Use of named functions
<script type="text/javascript"> function show(){ document.write('我是命名函数') } var f=show(); f();//函数调用 </script>
Global variables in functions can be accessed directly
Functions in functions need to be called first before they can be accessed
Column: Implement function calls within functions (calls of local functions)
<script type="text/javascript"> var num='laoli'; var f=function(num){ document.write(num+'真可爱'); function show(){ document.write('他不是女人') } show();//调用show()函数 } //执行函数 f(num); </script>
Result: Laoli is so cute, he is not a woman
Column: implement three calls
<script type="text/javascript"> //创建命名函数 function show(name, age) { document.write(name + '是男人,他' + age + '岁'); } //对象.函数应用 window.show('小明', '30'); //all方法调用函数 函数应用.( 调用者,参数1 ,参数2 , .....) show.call(window, '小明', '30'); //apply方法调用函数 apply(调用者,参数数组) show.apply(window, ['小明', '30']); </script>
Column: in the array Function call
<script type="text/javascript"> //show传入两个参数 1个数组 1个函数 function show(arr, func) { //func.call(window, arr); func.apply(window, [arr]) } show([1, 2, 3, 4], function(arr) { for (i in arr) { document.write(arr[i] + '<br/>') } }); </script>Result: [Related recommendations:
The above is the detailed content of What are the ways to call functions in javascript. For more information, please follow other related articles on the PHP Chinese website!