This article aims to provide basic knowledge of all JavaScript functions that a web developer must know.
Functions are not a fantasy world for software developers. If your daily activities involve coding, even a little bit, then at the end of the day, you must have created/modified one or more functions.
In short, a function is nothing more than a set of statements that perform a certain operation. A function may have some input parameters (used in the function body) and return a value after execution.
JavaScript functions also have these properties, but they are not just regular functions. JavaScript functions are objects. You can check out the article I once wrote about JavaScript objects, where I mentioned that almost everything in JavaScript is an object.
As objects, JavaScript functions may have properties and other functions (methods). Let's take a look at a typical function definition in JavaScript.
function myNotSoGreatFunc(visitor) { console.log("Welcome to Code Morning Mr. " + visitor); }
That’s right. The above function doesn't involve anything grand, as it simply welcomes visitors to the blog. But it shows what JavaScript functions look like. A function definition begins with the keyword function
, followed by the function name, empty or parentheses with parameters. The actual function code (JavaScript statement) is enclosed in a pair of curly braces { }. For functions, the return
statement is optional. JavaScript functions always return a value. When there is no return
statement in the function
body, then function
returns undefined.
The following code calls a function passing the visitor name as a parameter.
myNotSoGreatFunc("Bob Martin"); // Output: // Welcome to Code Morning Mr. Bob Martin.
So far, we understand the very basic characteristics of functions. Now, we'll take a look at some advanced concepts of JavaScript functions.
JavaScript functions can be anonymous. This means you can omit the function name from the function declaration. However, functions must be stored in variables.
var addNumbers = function (x, y) { return x + y; }
The above syntax is also called function expression. You can use the variable addNumbers
as the function name and call the function like below.
var sum = addNumbers(2, 3);
Function expressions are very convenient when you want to pass a function as a parameter to another function. Let's try to understand this using a simple example.
var add = function (first, second) { return first + second }; var multiply = function (first, second) { return first * second }; function calculate(fun, a, b) { return fun(a, b); }
First I have created two anonymous functions. The first returns the addition of two numbers, and the second returns the multiplication of two numbers. Pretty simple, nothing to show off. Then, I define the function calculate
, which accepts a function as the first argument followed by two arguments that accept two numbers.
I can call the function calculate by passing any function as the first argument.
var sum = calculate(add, 2, 3); // sum = 5 var multiplication = calculate(multiply, 2, 3); // multiplication = 6
You can see how easy it is to pass functions as parameters. This pattern is used heavily in AJAX when you pass a callback function to handle success or failure scenarios after the AJAX call is completed.
JavaScript is very flexible when it comes to passing or accessing function parameters. Let's look at the ways function parameters can be manipulated.
When a function is called, the function can have fewer or more parameters than required. If you call a function with fewer arguments than declared, the missing arguments are set to undefined.
function callMe(a, b, c) { console.log("c is " + typeof c); } callMe("Code", "Morning"); // Output: "c is undefined" callMe("Learn", "JavaScript", "Functions"); // Output: "c is string"
All JavaScript functions have a special object called arguments
, which is the argument array passed during the function call. This object can be used to access individual parameters or to obtain the total number of parameters passed to a function.
function callMe() { var i; for (i = 0; i < arguments.length; i++) { console.log(arguments[i]); } console.log("Total arguments passed: " + arguments.length); }
This function assumes no parameters are passed, but like I said, you can pass any number of parameters to a JavaScript function. I can call this function like this:
callMe("Code", "Morning", "Mr. Programmer"); // Output": // Code // Morning // Mr. Programmer // Total arguments passed: 3
Each argument can be accessed as an array item from the arguments
object. The total number of arguments
passed to the function can be obtained from the arguments.length property.
Are you a C++ or C#programmer? Have you ever seen a function that uses default parameters? Maybe you will answer yes! ECMAScript 6 brings this feature of JavaScript, that is, you can define functions with default parameters.
function greetMyVisitors(name, profession = "The cool programmer") { alert("Welcome Mr. " + name + ", " + profession); }
This function politely greets blog visitors. It has two parameters name
and profession
, and displays a welcome message in the message box. If no arguments (or "undefined") are passed during the call, the second argument takes the default value.
greetMyVisitors("Justin Bieber", "The singer"); // Shows the message "Welcome Mr. Justin Bieber, The singer" greetMyVisitors("Bob Martin"); // Shows the message "Welcome Mr. Bob Martin, The cool programmer" greetMyVisitors("John Papa", undefined); // Shows the message "Welcome Mr. John Papa, The cool programmer"
A function can contain one or more functions inside it. Inner functions may contain functions again internally. Let's take a look at the following operations.
function wakeUpAndCode() { function wakeUp() { console.log("I just woke up"); } function code() { console.log("I am ready to code now"); } wakeUp(); code(); } wakeUpAndCode(); // Output: // I just woke up // I am ready to code now
函数wakeUpAndCode
包含两个内部函数wakeUp
和code。当调用wakeUpAndCode时,函数主体开始执行函数主体。在外部函数中只有两个可执行语句,调用wakeUp
和code
的方法。调用wakeUp
将执行内部wakeUp
函数,这将写入string
“I just woke up”到控制台。调用code
将会写入“I am ready to code now”string
到控制台。
内部函数可以访问所有外部函数的变量和参数。内部函数是函数内部某种private
实现,并且不能从外部函数以外被调用。内部函数的使用生成了JavaScript闭包,这个我将另起一篇文章讨论。
IIFE是被立即调用执行的匿名函数表达式。IIFE看上去像这样:
(function() { // Your awesome code here }());
所有你要做的就是创建一个匿名函数,在函数定义后马上放一对圆括号以调用函数,最后将所有代码封装在另一对圆括号中。最外层的括号将它里面的所有一切转变成一个表达式,因为括号不能包含JavaScript语句。函数定义后面的圆括号则立即调用函数。
IIFE块中定义的任何变量或函数对块而言是本地的,并且不能被这个范围以外的任何代码改变。
看看IIFE的这个例子。此函数没有调用也会自动执行。
(function() { console.log("I run on my own."); }());
只需在plunker中复制并粘贴代码,看看在浏览器控制台中的输出。如果你不知道去哪里找浏览器控制台,那么只要在浏览器窗口中按下F12就会出现开发者工具。跳转console选项卡以查看console.log语句的所有输出。
IIFE是一个在代码中创建局部范围的很好方法。它们可以帮助你保护变量和函数,以避免被应用程序的其他部分更改或覆盖。JavaScript中IIFE的其他优势?它们是如何解决全局范围污染问题的?欢迎点击查看我关于立即执行函数表达式的文章。
函数可以充当构造器的角色,并且可以使用构造函数来创建新的对象。这是使JavaScript面向对象的特点之一。使用构造函数的好处是,你将能够通过预定义的属性和方法,创造尽可能多的对象。如果你由此关联到其他语言中的类和对象,那么你做的对。
让我们创建一个带有一些属性和方法的构造函数Programmer
。你可以假设它在你最喜欢的语言中是一个类。
function Programmer(name, company, expertise) { this.name = name; this.company = company; this.expertise = expertise; this.writeCode = function() { console.log("Writing some public static thing.."); } this.makeSkypeCall = function() { console.log("Making skype call.."); } this.doSalsa = function() { console.log("I'm a programmer, I can only do Gangnam style.."); } this.canWriteJavaScript = function() { return expertise === "JavaScript"; } }
函数有三个参数,并创建了一个具有三个属性和四种方法的对象。我不认为上面的代码需要任何解释。此外,我可以创建任意数量程序员对象。
var javaProgrammer = new Programmer("Mohit Srivastava", "Infosys", "Java"); var dotnetProgrammer = new Programmer("Atul Mishra", "Prowareness", ".NET");
虽然也可以创建一个使用对象文本语法带有相同属性和方法的对象,但我们需要多次编写相同的代码,这可不是什么伟大的实践。如果你知道编程DRY原则,那么你就不会不赞同我。构造函数使得可以一次定义对象,并创建真正的实例,无论什么时候你想要。
始终使用new关键字来从构造器创建新的对象。忘记了new
而像这个创建一个实例->
var jsProgrammer = Programmer("Douglas Crockford", "Yahoo", "JavaScript")
最终将添加所有属性和方法到全局的window
对象,哇哦,这将是太可怕了。原因是,除非明确指定,否则“this”指向全局的window
对象。使用new
设置“this”上下文到被创建的当前对象。
然而,有一种变通方法可以来克服这个问题。你可以改变构造函数的实现以使域安全,然后在创建新的对象时,你就可以愉快地忽略new
关键字了。请参见以下修改了的构造函数代码。为了便于查看,我已删除了一些方法。
function Programmer(name, company, expertise) { if(!(this instanceof Programmer)) { return new Programmer(name, company, expertise); } this.name = name; this.company = company; this.expertise = expertise; this.writeCode = function() { console.log("Writing some public static thing.."); } }
if
条件检查了this
对象是否是Programmer的一个实例。如果不是,它会创建一个新的Programmer
对象,并通过再次调用构造器返回相同的内容。
注意:你无法在不使用’new’关键字的情况下,在Strict
模式下从构造器创建一个新的对象。Strict
模式强制一些编码准则,并且在你写的东西不安全的情况下会抛出错误。要启用Strict
模式,你只需要添加在你的代码开头添加字符串 ‘use strict
’。在Strict模式下运行代码是一个良好的实践。
'use strict' function doSomething() { ... } .... ....
在这篇文章中,我几乎已经涵盖了有关函数的所有内容。函数被认为是JavaScript中的一等公民。理解函数可能是最重要的事情,如果你想掌握JavaScript的话。
欢迎各位指正。
The above is the content of in-depth understanding of functions in JavaScript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!