A function is a container for code statements and can be called using the bracketed ()
operator. Parameters can be passed within parentheses when calling so that certain values ??can be accessed by statements within the function when the function is called.
In the following code, we use the new
operator to create two versions of the addNumbers
function objectone, one using the more common literal mode. Both require two parameters. In each case, we call the function and pass the arguments in brackets to the ()
operator.
Example: sample76.html
<!DOCTYPE html><html lang="en"><body><script> var addNumbersA = new Function('num1', 'num2', 'return num1 + num2'); console.log(addNumbersA(2, 2)); // Logs 4. // Could also be written the literal way, which is much more common. var addNumbersB = function (num1, num2) { return num1 + num2; }; console.log(addNumbersB(2, 2)); // Logs 4. </script></body></html>
Functions can be used to return values, construct objects, or simply serve as a mechanism for running code. JavaScript has many uses for functions, but in their most basic form, functions are the only scope of executable statements.
Function()
Parameters
Function()
The constructor takes an unlimited number of arguments, but the last argument the Function()
constructor expects is a string containing the statements that make up the body of the function. Any arguments passed to the constructor before the last one are available to the function being created. You can also send multiple parameters as comma-separated strings.
In the code below, I contrast the usage of the Function()
constructor with the more common pattern of instantiating function objects.
Example: sample77.html
<!DOCTYPE html><html lang="en"><body><script> var addFunction = new Function('num1', 'num2', 'return num1 + num2'); /* Alternately, a single comma-separated string with arguments can be the first parameter of the constructor, with the function body following. */ var timesFunction = new Function('num1,num2', 'return num1 * num2'); console.log(addFunction(2, 2), timesFunction(2, 2)); // Logs '4 4' // Versus the more common patterns for instantiating a function: var addFunction = function (num1, num2) { return num1 + num2; }; // Expression form. function addFunction(num1, num2) { return num1 + num2; } // Statement form. </script></body></html>
It is not recommended or usually not recommended to directly utilize the Function()
constructor because JavaScript will use eval()
to parse the string containing the function logic. Many people think eval()
is unnecessary overhead. If it is used, there is most likely a flaw in the code design.
Using Function()
constructor without using the new
keyword has the same effect as using only the constructor to create a function object (new Function('x', 'return x')
and function(('x','return x')
).
Call directly Function()
No closure will be created when constructing the function.
Function()
Properties and methods
Function objects have the following properties (excluding inherited properties and methods):
Properties (Function.prototype;
):
prototype
Function object instance properties and methods
Function object instances have the following properties and methods (excluding inherited properties and methods):
Instance properties (var myFunction = function(x, y, z) {};
myFunction.length;
):
parameter
Constructor
length
Instance method (var myFunction = function(x, y, z) {};
myFunction.toString();
):
apply()
call()
toString()
Function always returns a value
While it is possible to create a function that simply executes a code statement, it is also common for the function to return a value. In the following example, we return a string from the sayHi
function.
Example: sample78.html
<!DOCTYPE html><html lang="en"><body><script> var sayHi = function () { return 'Hi'; }; console.log(sayHi()); // Logs "Hi". </script></body></html>
If the function does not specify a return value, it returns undefined
. In the following example, we call the yelp
function, which logs the string "yelp" to the console without explicitly returning a value.
Example: sample79.html
<!DOCTYPE html><html lang="en"><body><script> var yelp = function () { console.log('I am yelping!'); // Functions return undefined even if we don't. } /* Logs true because a value is always returned, even if we don't specifically return one. */ console.log(yelp() === undefined); </script></body></html>
The concept to remember here is that all functions return a value, even if you don't explicitly provide a value to return. If no return value is specified, the return value is undefined
.
Functions are first-class citizens (not just syntax, but also values)
In JavaScript, functions are objects. This means that functions can be stored in variables, arrays, or objects. Additionally, functions can be passed to or returned from functions. A function has properties because it is an object. All these factors make functions first-class citizens in JavaScript.
Example: sample80.html
<!DOCTYPE html><html lang="en"><body><script> // Functions can be stored in variables (funcA), arrays (funcB), and objects (funcC). var funcA = function () { }; // Called like so: funcA() var funcB = [function () { } ]; // Called like so: funcB[0]() var funcC = { method: function () { } }; // too.method() or funcC['method']() // Functions can be sent to and sent back from functions. var funcD = function (func) { return func }; var runFuncPassedToFuncD = funcD(function () { console.log('Hi'); }); runFuncPassedToFuncD(); // Functions are objects, which means they can have properties. var funcE = function () { }; funcE.answer = 'yup'; // Instance property. console.log(funcE.answer); // Logs 'yup'. </script></body></html>
It is crucial to realize that a function is an object and therefore a value. It can be passed or enhanced like any other expression in JavaScript.
Pass parameters to function
Parameters are tools for passing values ??into the function scope when calling a function. In the example below, we call addFunction()
. Since we have predefined it to take two parameters, two additional values ??are available within its scope.
Example: sample81.html
<!DOCTYPE html><html lang="en"><body><script> var addFunction = function (number1, number2) { var sum = number1 + number2; return sum; } console.log(addFunction(3, 3)); // Logs 6. </script></body></html>
In contrast to some other programming languages, it is perfectly legal to omit parameters in JavaScript, even if the function has been defined to accept these parameters. Missing parameters are only assigned the value undefined
. Of course, if the parameter value is omitted, the function may not work properly.
If you pass unexpected parameters to the function (parameters that were not defined when the function was created), no error will occur. And these arguments can be accessed from the arguments
object, which is available to all functions.
this
和 arguments
值可用于所有函數(shù)
在所有函數(shù)的范圍和主體內(nèi),this
和 arguments
值可用。
arguments
對象是一個類似數(shù)組的對象,包含傳遞給函數(shù)的所有參數(shù)。在下面的代碼中,即使我們在定義函數(shù)時放棄指定參數(shù),我們也可以依賴傳遞給函數(shù)的 arguments
數(shù)組來訪問在調(diào)用時發(fā)送的參數(shù)。
示例:sample82.html
<!DOCTYPE html><html lang="en"><body><script> var add = function () { return arguments[0] + arguments[1]; }; console.log(add(4, 4)); // Returns 8. </script></body></html>
this
關(guān)鍵字,傳遞給所有函數(shù),是對包含該函數(shù)的對象的引用。正如您所期望的,對象中包含的作為屬性(方法)的函數(shù)可以使用 this
來獲取對父對象的引用。當(dāng)函數(shù)定義在全局作用域時,this
的值為全局對象。查看以下代碼并確保您了解 this
返回的內(nèi)容。
示例:sample83.html
<!DOCTYPE html><html lang="en"><body><script> var myObject1 = { name: 'myObject1', myMethod: function () { console.log(this); } }; myObject1.myMethod(); // Logs 'myObject1'. var myObject2 = function () { console.log(this); }; myObject2(); // Logs window. </script></body></html>
arguments.callee
屬性
arguments
對象有一個名為 callee
的屬性,它是對當(dāng)前正在執(zhí)行的函數(shù)的引用。此屬性可用于從函數(shù)范圍內(nèi)引用該函數(shù) (arguments.callee
)a 自引用。在下面的代碼中,我們使用此屬性來獲取對調(diào)用函數(shù)的引用。
示例:sample84.html
<!DOCTYPE html><html lang="en"><body><script> var foo = function foo() { console.log(arguments.callee); // Logs foo() // callee could be used to invoke recursively the foo function (arguments.callee()) } (); </script></body></html>
當(dāng)需要遞歸調(diào)用函數(shù)時,這非常有用。
函數(shù)實例 length
屬性和 arguments.length
arguments
對象具有唯一的 length
屬性。雖然您可能認(rèn)為這個 length 屬性將為您提供已定義參數(shù)的數(shù)量,但它實際上提供了在調(diào)用期間發(fā)送到函數(shù)的參數(shù)數(shù)量。
示例:sample85.html
<!DOCTYPE html><html lang="en"><body><script> var myFunction = function (z, s, d) { return arguments.length; }; console.log(myFunction()); // Logs 0 because no parameters were passed to the function. </script></body></html>
使用所有 Function()
實例的 length
屬性,我們實際上可以獲取函數(shù)期望的參數(shù)總數(shù)。
示例:sample86.html
<!DOCTYPE html><html lang="en"><body><script> var myFunction = function (z, s, d, e, r, m, q) { return myFunction.length; }; console.log(myFunction()); // Logs 7. </script></body></html>
arguments.length
屬性在 JavaScript 1.4 中已棄用,但可以從函數(shù)對象的 length
屬性訪問發(fā)送到函數(shù)的參數(shù)數(shù)量。接下來,您可以通過利用 callee
屬性來首先獲取對正在調(diào)用的函數(shù)的引用 (arguments.callee.length
) 來獲取長度值。
重新定義函數(shù)參數(shù)
函數(shù)參數(shù)可以直接在函數(shù)內(nèi)部重新定義,也可以使用 arguments
數(shù)組??匆幌逻@段代碼:
示例:sample87.html
<!DOCTYPE html><html lang="en"><body><script> var foo = false; var bar = false; var myFunction = function (foo, bar) { arguments[0] = true; bar = true; console.log(arguments[0], bar); // Logs true true. } myFunction(); </script></body></html>
請注意,我可以使用 arguments
索引或直接為參數(shù)重新分配新值來重新定義 bar 參數(shù)的值。
在函數(shù)完成之前返回函數(shù)(取消函數(shù)執(zhí)行)
通過使用帶或不帶值的 return
關(guān)鍵字,可以在調(diào)用期間隨時取消函數(shù)。在下面的示例中,如果參數(shù)未定義或不是數(shù)字,我們將取消 add
函數(shù)。
示例:sample88.html
<!DOCTYPE html><html lang="en"><body><script> var add = function (x, y) { // If the parameters are not numbers, return error. if (typeof x !== 'number' || typeof y !== 'number') { return 'pass in numbers'; } return x + y; } console.log(add(3, 3)); // Logs 6. console.log(add('2', '2')); // Logs 'pass in numbers'. </script></body></html>
這里要講的概念是,您可以在函數(shù)執(zhí)行過程中的任何時刻使用 return
關(guān)鍵字來取消函數(shù)的執(zhí)行。
定義函數(shù)(語句、表達式或構(gòu)造函數(shù))
函數(shù)可以用三種不同的方式定義:函數(shù)構(gòu)造函數(shù)、函數(shù)語句或函數(shù)表達式。在下面的示例中,我演示了每種變體。
示例:sample89.html
<!DOCTYPE html><html lang="en"><body><script> /* Function constructor: The last parameter is the function logic, everything before it is a parameter. */ var addConstructor = new Function('x', 'y', 'return x + y'); // Function statement. function addStatement(x, y) { return x + y; } // Function expression. var addExpression = function (x, y) { return x + y; }; console.log(addConstructor(2, 2), addStatement(2, 2), addExpression(2, 2)); // Logs '4 4 4'. </script></body></html>
有人說函數(shù)還有第四種類型的定義,稱為“命名函數(shù)表達式”。命名函數(shù)表達式只是一個包含名稱的函數(shù)表達式(例如, var add = function add(x, y) {return x+y}
)。
調(diào)用函數(shù)(函數(shù)、方法、構(gòu)造函數(shù)或 call()
和 apply()
)
使用四種不同的場景或模式調(diào)用函數(shù)。
- 作為函數(shù)
- 作為一種方法
- 作為構(gòu)造函數(shù)
- 使用
apply()
或call()
在下面的示例中,我們將檢查每種調(diào)用模式。
示例:sample90.html
<!DOCTYPE html><html lang="en"><body><script> // Function pattern. var myFunction = function () { return 'foo' }; console.log(myFunction()); // Logs 'foo'. // Method pattern. var myObject = { myFunction: function () { return 'bar'; } } console.log(myObject.myFunction()); // Logs 'bar'. // Constructor pattern. var Cody = function () { this.living = true; this.age = 33; this.gender = 'male'; this.getGender = function () { return this.gender; }; } var cody = new Cody(); // Invoke via the Cody constructor. console.log(cody); // Logs the cody object and properties. // apply() and call() pattern. var greet = { runGreet: function () { console.log(this.name, arguments[0], arguments[1]); } } var cody = { name: 'cody' }; var lisa = { name: 'lisa' }; // Invoke the runGreet function as if it were inside of the cody object. greet.runGreet.call(cody, 'foo', 'bar'); // Logs 'cody foo bar'. // Invoke the runGreet function as if it were inside of the lisa object. greet.runGreet.apply(lisa, ['foo', 'bar']); // Logs 'lisa foo bar'. /* Notice the difference between call() and apply() in how parameters are sent to the function being invoked. */ </script></body></html>
確保您了解所有四種調(diào)用模式,因為您將遇到的代碼可能包含其中任何一種。
匿名函數(shù)
匿名函數(shù)是沒有給出標(biāo)識符的函數(shù)。匿名函數(shù)主要用于將函數(shù)作為參數(shù)傳遞給另一個函數(shù)。
示例:sample91.html
<!DOCTYPE html><html lang="en"><body><script> // function(){console.log('hi');}; // Anonymous function, but no way to invoke it. // Create a function that can invoke our anonymous function. var sayHi = function (f) { f(); // Invoke the anonymous function. } // Pass an anonymous function as a parameter. sayHi(function () { console.log('hi'); }); // Logs 'hi'. </script></body></html>
自調(diào)用函數(shù)表達式
函數(shù)表達式(實際上是除從 Function()
構(gòu)造函數(shù)創(chuàng)建的函數(shù)之外的任何函數(shù))可以在定義后使用括號運算符立即調(diào)用。在以下示例中,我們創(chuàng)建 sayWord()
函數(shù)表達式,然后立即調(diào)用該函數(shù)。這被認(rèn)為是一個自調(diào)用函數(shù)。
示例:sample92.html
<!DOCTYPE html><html lang="en"><body><script> var sayWord = function () { console.log('Word 2 yo mo!'); } (); // Logs 'Word 2 yo mo!' </script></body></html>
自調(diào)用匿名函數(shù)語句
可以創(chuàng)建自調(diào)用的匿名函數(shù)語句。這稱為自調(diào)用匿名函數(shù)。在下面的示例中,我們創(chuàng)建了幾個立即調(diào)用的匿名函數(shù)。
示例:sample93.html
<!DOCTYPE html><html lang="en"><body><script> // Most commonly used/seen in the wild. (function (msg) { console.log(msg); })('Hi'); // Slightly different, but achieving the same thing: (function (msg) { console.log(msg) } ('Hi')); // The shortest possible solution. !function sayHi(msg) { console.log(msg); } ('Hi'); // FYI, this does NOT work! // function sayHi() {console.log('hi');}(); </script></body></html>
根據(jù) ECMAScript 標(biāo)準(zhǔn),如果要立即調(diào)用函數(shù),則需要在函數(shù)兩邊加上括號(或?qū)⒑瘮?shù)轉(zhuǎn)換為表達式的任何內(nèi)容)。
函數(shù)可以嵌套
函數(shù)可以無限期地嵌套在其他函數(shù)中。在下面的代碼示例中,我們將 goo
函數(shù)封裝在 bar
函數(shù)內(nèi)部,該函數(shù)位于 foo
函數(shù)內(nèi)部。
示例:sample94.html
<!DOCTYPE html><html lang="en"><body><script> var foo = function () { var bar = function () { var goo = function () { console.log(this); // Logs reference to head window object. } (); } (); } (); </script></body></html>
這里的簡單概念是函數(shù)可以嵌套,并且嵌套的深度沒有限制。
請記住,嵌套函數(shù)的 this
的值將是 JavaScript 1.5、ECMA-262 第 3 版中的頭對象(Web 瀏覽器中的 window
對象)。
將函數(shù)傳遞給函數(shù)以及從函數(shù)返回函數(shù)
如前所述,函數(shù)是 JavaScript 中的一等公民。由于函數(shù)是一個值,并且函數(shù)可以傳遞任何類型的值,因此函數(shù)可以傳遞給函數(shù)。接受和/或返回其他函數(shù)的函數(shù)有時稱為“高階函數(shù)”。
在下面的代碼中,我們將一個匿名函數(shù)傳遞給 foo
函數(shù),然后立即從 foo
函數(shù)返回。變量 bar
所指向的正是這個匿名函數(shù),因為 foo
接受并返回匿名函數(shù)。
示例:sample95.html
<!DOCTYPE html><html lang="en"><body><script> // Functions can be sent to, and sent back from, functions. var foo = function (f) { return f; } var bar = foo(function () { console.log('Hi'); }); bar(); // Logs 'Hi'. </script></body></html>
因此,當(dāng)調(diào)用 bar
時,它會調(diào)用傳遞給 foo()
函數(shù)的匿名函數(shù),然后從 foo()
函數(shù)傳回并從 bar
引用多變的。所有這些都是為了展示函數(shù)可以像任何其他值一樣傳遞的事實。
在定義函數(shù)語句之前調(diào)用函數(shù)語句(又名函數(shù)提升)
函數(shù)語句可以在執(zhí)行期間在其實際定義之前調(diào)用。這有點奇怪,但您應(yīng)該意識到這一點,以便您可以利用它,或者至少知道當(dāng)您遇到它時會發(fā)生什么。在下面的示例中,我在定義 sayYo()
和 sum()
函數(shù)語句之前調(diào)用它們。
示例:sample96.html
<!DOCTYPE html><html lang="en"><body><script> // Example 1 var speak = function () { sayYo(); // sayYo() has not been defined yet, but it can still be invoked, logs 'yo'. function sayYo() { console.log('Yo'); } } (); // Invoke // Example 2 console.log(sum(2, 2)); // Invoke sum(), which is not defined yet, but can still be invoked. function sum(x, y) { return x + y; } </script></body></html>
發(fā)生這種情況是因為在代碼運行之前,函數(shù)語句被解釋并添加到執(zhí)行堆棧/上下文中。確保您在使用函數(shù)語句時意識到這一點。
定義為函數(shù)表達式的函數(shù)不會被提升。僅提升函數(shù)語句。
函數(shù)可以調(diào)用自身(又名遞歸)
函數(shù)調(diào)用自身是完全合法的。事實上,這經(jīng)常被用在眾所周知的編碼模式中。在下面的代碼中,我們啟動 countDownFrom
函數(shù),然后該函數(shù)通過函數(shù)名稱 countDownFrom
調(diào)用自身。本質(zhì)上,這會創(chuàng)建一個從 5 倒數(shù)到 0 的循環(huán)。
示例:sample97.html
<!DOCTYPE html><html lang="en"><body><script> var countDownFrom = function countDownFrom(num) { console.log(num); num--; // Change the parameter value. if (num < 0) { return false; } // If num < 0 return function with no recursion. // Could have also done arguments.callee(num) if it was an anonymous function. countDownFrom(num); }; countDownFrom(5); // Kick off the function, which logs separately 5, 4, 3, 2, 1, 0. </script></body></html>
您應(yīng)該意識到,函數(shù)調(diào)用自身(也稱為遞歸)或重復(fù)執(zhí)行此操作是很自然的。
結(jié)論
函數(shù)是 JavaScript 最常用的方面之一,希望您現(xiàn)在對如何使用它們有了更好的了解。
The above is the detailed content of Re-title: execute function(). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has
