Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the syntax of JavaScript functions?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what the syntax of JavaScript functions are, and the editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

I. ordinary function

Js's function creation is quite special, there are many ways, the simplest one is similar to the c language.

Features:

Function names can have "$" characters in addition to letters, numbers, and underscores.

In js, the function name is a variable that stores the function object. Use the typeof keyword to view function types. (this concept is similar to python, where you can take over this function with other variables.)

There is no need to write keywords when defining function parameters: var, let, const. The default should be locally modifiable variables.

Input parameters are not checked in JS syntax. This means that the input parameters can be less or more. Less input undefined instead, more automatic ignore.

Similarly, JS is not restricted to whether there is a return value, all have a return value. If the return value is not specified, an invalid value is returned.

/ 1. Function Definitionfunction printHello_1 $_ (name_0) {/ / execution console.log ("Hello World!" + name_0);} console.log (typeof printHello_1 $_); / / 2. Function InvocationprintHello_1 $_ (); / / 3. Function Naming// 4. Function Parameters// 5. Function Return

Js also supports anonymous functions, but does not write function names. There is something similar in python, and it is also recorded in python's study notes: the lambda anonymous function.

/ / 6. The function can also be created without a name. Let him = function () {console.log ("him");} him () / / reflects that the name is actually a variable name. / / 8. The function name itself does not support passing assignments, but variables can. / / him = printHello_1 (); / / report an error (it's a bit like an array definition and then you can no longer assign values? Let add = him;add (); / / 7. This variable can still be assigned to something else. Him = 6position console.log (him) / / output number 6 II. Arrow function

The arrow function in js is a "veritable" anonymous function, which can quickly create the functional body of nested functions (self-created words). It is also more appropriate to python's usage of lambda anonymous functions.

When looking at the actual combat cases, it is all the creation and transmission of this anonymous function, and the first contact is too confusing. In the following code, in order to see the effect, I will change the unused part to fake and block the operation. You ask why you don't comment directly? Because I want to exercise and use it.

The method seems simple, with the parentheses in front of the parameters and the arrow followed by the code. If it is a single line of simple code, you don't need to write parentheses, and the single line also comes with an implicit return of the calculated value.

If (false) {const add = (a, b) = > a + b; / / similar to creating a function directly and throwing it to a variable call. Console.log (add (1Magazine 3)); / / No return value is written, and the calculated value} if (false) {let add = (a, b) = > a + b; console.log (add (1Magazine 3)) is implicitly returned; / / print 4 const add_0 = add; / / A normal variable assignment can replace add = 5 / / you can see whether the essence is a variable. If the definition uses variable types, you can change console.log (add); / / print 5 console.log (add_0 (2,4)); / / print 6} if (false) {console.log (add_0 (10,4)); / / const variable types cannot cross scope}

If you need a line break, you need to use large parentheses. Commonly used.

If (false) {const add = (a, b) = > {return a + b;} console.log (add (1Power3)); / / has a return value, indicating that if you use curly braces, you can indicate a line break but there will be no implicit return. There is always an implicit return for a single line. } III. Packet JSON

JSON (JavaScript Object Notation, JS object Spectrum) is a lightweight data exchange format. It is based on a subset of ECMAScript, the js specification developed by the European computer Association, and uses a text format that is completely independent of the programming language to store and represent data. The concise and clear hierarchical structure makes JSON an ideal data exchange language. It is easy for people to read and write, at the same time, it is also easy for machine analysis and generation, and effectively improve the efficiency of network transmission. [as of encyclopedia]

I also came into contact with this kind of packet when learning neural network and ros before, a small suffix .json file containing a bunch of parameters or data sets. In terms of format, it looks a lot like a dictionary, with pairs of keys and values. If you expand graphically, it is actually a list with headers and data.

Js provides the Object class to create json objects. (in fact, it is to create an object, which will be described in more detail in the next section)

/ / example 1if (false) {const book = new Object ({title: "1984", author: "George Orwell"}) / / create JSON object console.log ("\ n -") console.log (typeof book) / / View type is indeed object console.log (book) / / can print normally} / / example 2 (described in the next section) Knowledge points of the object) if (false) {const book = ({title: "1984", author: "George Orwell"}) / / even without the keyword Object can have the same effect. Console.log ("\ n -") console.log (typeof book) console.log (book)} / / example 3if (false) {const book = [{title: "1984", author: "George Orwella"}, {title: "1985", author: "George Orwellb"}, {title: "1986", author: "George Orwellc"}, {title: "1987" Author: "George Orwelld"}] console.log ("\ n -") console.log (typeof book) / / print type or object object But actually one is an array console.log (book)}

Js provides a method for converting json object data to strings: JSON.stringify ().

If (false) {const book = ({title: "1984", author: "George Orwell"}) / / even without the keyword Object can have the same effect. Console.log ("\ n -") let bookJSON = JSON.stringify (book); / / keep the object in its original format and convert it to a string, where the key name becomes a string (that is, in double quotes)? Convenient for saving in text? Console.log (typeof bookJSON) / / come to think of it, JSON is also the parameter file I used to write the ros project, and the text file of Baidu Flying slurry is in this format. The output of console.log (bookJSON)} / * is as follows:-string {"title": "1984", "author": "George Orwell"} * / / you can find that the key value is still the original string, but the key name has been transformed into a string

I did an analogy experiment and see the following notes.

If (false) {const book = console.log ("\ n -") console.log (typeof book) / / type still belongs to object let bookJSON = JSON.stringify (book); / / can still be called without error. Console.log (typeof bookJSON) / / gets a string that is exactly the same as the original. The output of console.log (bookJSON)} / * is as follows:-objectstring [1dje 23jol 3, "156"] * / / you can find that the function doesn't seem to work. Judging that the format does not meet the json requirements will not work and will not report an error.

Js provides a method for converting string data into json objects: JSON.parse (). This is the inverse operation of JSON.stringify ().

If (false) {let data_0 = "[1Power2jue 3]"; let data = "{\" title\ ":\" 1984\ ",\" author\ ":\" George Orwell\ "}"; / / Note that in the string form of JSON, keys and values are put in double quotation marks to make it similar to a string. If there is something wrong, the conversion will fail. Let parsed = JSON.parse (data); / / reverse operation to change the string back to the object type. It parses whether it conforms to the format. The output of console.log ("\ n -") console.log (parsed); / / console.log (typeof parsed) console.log (typeof data)} / * is as follows:-{title: '1984, author:' George Orwell'} objectstring*/// need to note that the diagonal bar in the string is troublesome.

It's important to learn how to use data in JSON format. Json variables are not ordinary data, but objects that contain many data processing functions. For example, the above two strings and data conversion between the function, check used in the actual combat. They are the two operations of reading data and storing data respectively.

4. Object Object

Objects in js create classes different from python, but create objects directly. I will look at the example directly and expand it with the example.

If (false) {let data_0 = "[1Power2jue 3]"; let data = "{\" title\ ":\" 1984\ ",\" author\ ":\" George Orwell\ "}"; / / Note that in the string form of JSON, keys and values are put in double quotation marks to make it similar to a string. If there is something wrong, the conversion will fail. Let parsed = JSON.parse (data); / / reverse operation to change the string back to the object type. It parses whether it conforms to the format. The output of console.log ("\ n -") console.log (parsed); / / console.log (typeof parsed) console.log (typeof data)} / * is as follows:-{title: '1984, author:' George Orwell'} objectstring*/// need to note that the diagonal bar in the string is troublesome.

As can be seen from the format, it feels like a bunch of attributes, with strings and anonymous functions. And instead of using the equal sign, the value is assigned with a colon, just like the key pair in a dictionary.

So now it seems that, in fact, json packets are equivalent to the existence of objects in js. If it is a direct print function method, it will output a character like [Function (anonymous)].

In addition to directly assigning values at the beginning, you can also create empty objects first and then add values step by step. If an attribute that already exists will be overwritten, otherwise it will be treated as an addition. (very simple and rude)

/ / 2. Another way to create an object is to use the constructor to create if (false) {const book = new Object (); console.log (book); / / initially create an empty console.log (typeof book); / / the type is object book.title = "1984"; book.author = "George Orwell"; book.isAvailable = false; / / add attribute book.checkIn = function () {this.isAvailable = true / / add method}; book.checkOut = function () {this.isAvailable = false;}; console.log (book); / / print normal console.log (typeof book); / / 3. The method to access the elements in the object: console.log (book.title); / / similar structure access console.log (book ["title"]); / / similar dictionary access, the output result is the same, note, such access, the key name must be in double quotes, as a string form console.log (book.checkIn); / / if it is an access function, if there are no parentheses, the object will be returned. Print similar characters: [Function (anonymous)] console.log (book.checkIn ()); / / if parentheses are equivalent to calling execution. (the return value is empty, because the return value is not used to write the return value within the function) console.log (book ["checkIn"]); / / can also be accessed in the form of a dictionary, the result is the same console.log (book ["checkIn"] ()); / / this parenthesis is outside the square brackets. }

Context mechanism: this, does not exactly refer to the name of the object inside the object, but refers to the variable used by the context? (I don't understand it very thoroughly when I watch the video explanation.)

Similar to the body I use, the body I use is the object, the object is returned, and the function I use is the function. So this can also be used in functions, even though the function itself is an object (? ).

If (false) {const bookObj = {/ / create an object checkIn: function () {/ / add an attribute return this / / this property is a method with a return value that returns the object itself} function anotherCheckIn () {/ / create a function return this; / / return a function itself} console.log (bookObj.checkIn () = = bookObj) / / whether the return value is the object itself, the correct console.log (bookObj.checkIn ()) = = globalThis); / / whether the returned value is a function, the wrong console.log (anotherCheckIn () = = globalThis); / / whether the returned value is a function, correct} V, Promise

The ignorant section talks about the asynchronous operation mechanism in js? Without much explanation, I am afraid that the more I say it, the more wrong it will become.

The / / Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value. If (true) {function promiseTimeout (ms) {/ / create a function return new Promise ((resolve, reject) = > {/ /) returns a Promise object. The input parameter is an anonymous function, where the anonymous function has two parameters, one is the content that will be executed on success, and the other is the content setTimeout (resolve, ms) that will be executed on failure. / / js internal function that delays the second parameter ms and executes the contents of the first parameter. });} promiseTimeout (2000) / / calls the function, passing in the parameter 2000ms; .then () = > {/ / the built-in method of the returned Promise object; if successful, it will be called. The built-in method also has a parameter, which is the anonymous function console.log ('callbacks'); / / the anonymous function has no input parameters, and the internal function is to print return promiseTimeout (1000). / / call the function again and return another variable}). Then (() = > {/ / because another variable is returned above, it can be called chained, console.log ('Also additional variables'); / / delay 1000ms, and then call return Promise.resolve (42) after a successful run / / return another object, infinite nesting doll}) .then ((result_0) = > {/ / input parameter. The name of this parameter is arbitrary, and I can still achieve the effect after I modify it. Ide automatically marks red, so you should be able to know that it is a variable, not the syntax keyword console.log (result_0); / / print parameter}) .catch () = > {/ / ditto, but call console.log ('error') on failure }) / / because the Promise.prototype.then and Promise.prototype.catch methods return promise, they can be called chained. } / * the running result is: wait a moment to print a line: Done! Wait a moment and then print two lines at the same time: Also done! 42 / 6. Async: Await

Contrary to the Promise mechanism.

/ / Async:Awaitfunction promiseTimeout (ms) {return new Promise ((resolve, reject) = > {setTimeout (resolve, ms);});} async function longRunningOperation () {return 42;} async function run () {console.log ('startup'); await promiseTimeout (2000); / / add the await keyword, and the result is similar to desynchronization. Originally, the use of Promise will make printing first, then delay, if you add A _ A _ A, it will delay first and then print in order. Const response = await longRunningOperation (); console.log (response); / / it should return 42 directly and print. In fact, if you don't add the await keyword, you will immediately return a Promise object instead of 42. Console.log ('stop printing');} run (); / * the running result is: print a line: Start! Wait a moment and then print two lines at the same time: 42Stop! * / 7. Bag

Using the nvm tool that comes with node.js, you can manage js packages very well. And the project can be equipped with relevant software package catalogs. You only need to add the corresponding software package to it, and then enter the update project instruction to add the software package to the project.

It's similar to compiling, but this is a download. In the past, python advocated that software packages should be installed directly in the computer workspace. The related library of c language is recommended in the project. Js is also advocated in the project. However, if you want to transfer the program, you will talk about deleting the package folder. Transfer only the part of the project code. After the transfer, you can use the update download function on other computers. This operation is a bit like the ros project I learned before. However, the ros project can run normally even if it is not set correctly. If the setting of js is not accurate, it will not pass at compile time.

This is the end of this article on "what is the syntax of JavaScript functions?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report