Home > Web Front-end > JS Tutorial > Detailed explanation of function declaration and call in JavaScript

Detailed explanation of function declaration and call in JavaScript

零下一度
Release: 2017-06-26 10:37:41
Original
1414 people have browsed it

In JavaScript, functions exist as first-class members. Therefore, it is very necessary to master the knowledge of functions in JavaScript. In the past few days, I have read the first part of Chapter 3 and Chapter 4 of JavaScript Ninja. A summary.

JavaScript function declaration:

JavaScript functions are declared using function literals to create functions.

Shaped like

function name(arg1,arg2)//函数的名称可选
{
  code;
};
Copy after login

Function scope:

There is no block-level scope in JavaScript, only function scope. That is to say, in JavaScript, scope is declared by functions, not by code blocks.

{var a=10;
}
console.log(a);//结果是10
Copy after login
function a()
{var a=10;
}
console.log(a);//结果是undefined
Copy after login

Function call:

1. Call as a function

function a()
{};
a();
Copy after login

2. Call as a method

var o={};
o.haha=function();
haha();
Copy after login

3. Call as a constructor

function Pig()
{};var xiaohong=new Pig();var xiaoming=new Pig();
Copy after login

4. Call using the apply and call methods

function haha()
{};var hahaha1={};var hahaha2={};
haha.apply(hahaha1,[1,2,3,4]);//apply方法第一个参数是函数上下文的对象,第二个参数是要传入参数的数组haha.call(hahaha2,1,2,3,4);call方法的第一个参数是函数上下文的对象,剩下的参数是要传入的参数
Copy after login

The above is the detailed content of Detailed explanation of function declaration and call in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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