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

Detailed explanation of function declaration and call in JavaScript

零下一度
零下一度Original
2017-06-26 10:37:411418browse

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;
};

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
function a()
{var a=10;
}
console.log(a);//结果是undefined

Function call:

1. Call as a function

function a()
{};
a();

2. Call as a method

var o={};
o.haha=function();
haha();

3. Call as a constructor

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

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方法的第一个参数是函数上下文的对象,剩下的参数是要传入的参数

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!

Statement:
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