In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "detailed explanation of the basic functions and methods of JavaScript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the detailed explanation of JavaScript basic functions and methods".
Catalogue
I. the difference between function and method
Second, how to write a function well
2.1 accurate naming
2.1.1 function naming
2.1.2 Parameter naming
2.2 function comments
2.2.1 Parameter comments
2.3 function parameters
2.3.1 Parameter default value
2.3.2 object parameters
2.3.3 number of parameters
2.3.4 Parameter type defense
2.4 return of function
2.4.1 idempotent function
2.4.2 Pure function
2.4.3 return null
The difference between function and method
I. the difference between function and method
Function (function): a function is a JavaScript code snippet with a name and parameters that can be defined multiple calls at a time.
Method (method): when a function is written with an object, the function becomes a "method." for example, when a function is assigned to an object's properties, we call it a "method."
Second, how to write a function well
In JS, in addition to variables, the most used should be the function, the function is the first citizen of Javascript.
2.1 accurate naming
2.1.1 function naming
The naming of the function needs to be clear, semantic clear, and simply summarize the function of the function. Let's not think about shortening the function name because the code is short, which does not improve performance or efficiency. On the contrary, if a function name is not clear enough, it is often impossible for others to understand.
Try to use verbs, such as getXxxxx and setXxxxx. If the verb comes first, the semantics will be clearer.
2.1.2 Parameter naming
Emphasizing semantics, parameter naming gives the caller a clearer idea of what to pass in and what parameters to correspond to. Of course, like some generic names are acceptable, like callback,fn, even without looking at the comments, I often know what the parameters here are going to do and what to pass.
2.2 function comments
/ * * @ param {(Date | number)} date-time * @ param {string} unit-conversion format * / export const timeFormat = (date: Date | number | string, unit: string) = > {if (! date) {return'} if (typeof date = 'string') return date; if (typeof date =' number') {date = new Date (date) } const year = date.getFullYear (); const month = date.getMonth () + 1; const day = date.getDate (); const hour = date.getHours (); const minute = date.getMinutes (); const second = date.getSeconds (); if (unit = 'year') return `${year}`; if (unit = =' month') return `${year}-${month}`; if (unit = 'day') return `${year}-${month}-${day}` If (unit = = 'hour') return `${year}-${month}-${day} ${hour}`; if (unit =' minute') return `${year}-${month}-${day} ${hour}: ${minute}`; if (unit = 'second') return `${year}-${month}-${day} ${hour}: ${minute}: ${second}`;} 2.2.1 Parameter Notes
/ * time formatting tool function * * @ param {(Date | number)} date-time * @ param {string} unit-conversion format * /
@ param {type} Parameter-Parameter explanation: type indicates the type of parameter, such as string,number. When there are multiple parameter types, you can identify {(string | string [])}, indicating that the parameter can be a string or an array of strings.
Object properties: each property of the object needs to be explained
/ * @ param {Object} employee-Project employee * @ param {string} employee.name-name of the project employee * @ param {string} employee.department-Department of the project employee * / Project.prototype.assign = function (employee) {/ /.}
Optional parameters:
/ * time formatting tool function * * @ param {(Date | number | string)} date-time * @ param {string} [unit]-conversion format * / export const timeFormat = (date: Date | number | string, unit: string) = > {/ /.}
Default value:
/ * time formatting tool function * * @ param {(Date | number)} date-time * @ param {string} [unit = 'second']-conversion format * / export const timeFormat = (date: Date | number | string, unit =' second') = > {/...} 2.3 function parameters
2.3.1 Parameter default value
Export const timeFormat = (date: Date, unit = 'second') = > {/...} 2.3.2 object parameters
Async function printer_proxy_print (html_str: string, file_path: string, device: string | undefined, orientation: number, printer_mode: string, width: number, height: number, scale: number, from: number, to: number, left_offset: number, top_offset: number, pdf_tools: string | undefined, begin_page = 1, end_page = 1, repeat_times = 1, print_type: string) {/ /.}
You can give the parameter the default value, so you can pass only the first few necessary parameters, like this.
Async function printer_proxy_print (html_str: string, file_path: string, device = 'pc', orientation =' xxx', printer_mode = 'xxx', width = 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,12 Print_type = 'base64') {/ /...} await printer_proxy_print (html_str, file_path)
The above method seems feasible, but in fact, when one of my parameters is different, I need to pass all the parameters in front of this parameter. This is obviously not feasible. So when there are many parameters, we need to pass parameters by means of object deconstruction.
Async function printer_proxy_print ({html_str, file_path, device = 'pc', orientation =' xxx', printer_mode = 'xxx', width = 123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123,123, Print_type = 'base64'}) {/ /...} await printer_proxy_print ({html_str, file_path})
The advantage of deconstruction is that I can pass some of the parameters I want without worrying about the order. However, functions with so many parameters often have problems (specific analysis of specific problems). That is, the problem of the number of parameters mentioned below.
2.3.3 number of parameters
The fewer parameters of a function, the better, no more than 3 at most. More parameters often mean more relationships and more logical crossover relative. When testing, it is often difficult to cover all the conditions, and the probability of problems increases.
When there are many parameters, sometimes it means more functions, which violates the principle of single function.
2.3.4 Parameter type defense
Before TS development, we do not know what users will send in, this time is often prone to type errors, or, we want to achieve compatibility, like the previous timeFormat function, we hope that when users call, they can want to format the time object or timestamp, then we need to do a defensive treatment.
If (! date) {return''} if (typeof date = 'string') return date; if (typeof date =' number') {date = new Date (date);}
It is worth noting, however, that even if we use TS, we can avoid parameter type problems in most cases, but this is not absolute, because we sometimes accept the data returned by the interface directly.
We often say, never trust the user's input, similarly, I do not believe the data returned by the interface, we can not guarantee that the back end will not go wrong, the agreed parameter is the array type, how can you give me a null when it is empty?
Of course, these situations sometimes require trial and error, and sometimes as much as we can think of, don't be lazy and write down the type judgment.
2.4 return of function
2.4.1 idempotent function
What is idempotent, to put it simply, what is input and what is output is fixed, the input parameter determines the output parameter, no matter how many times it is called, as long as the input is the same, the result should remain the same.
Function sum (a: number, b: number) {return a + b;}
Idempotent functions are maintainable and relatively easy to unit test.
2.4.2 Pure function
Under idempotent conditions, pure functions also require no side effects.
Const dog = {name: 'puppy', age: 2, weight: 30,} if (! dog.color) {console.log (' has no color');} function addColor (dog) {dog.color = 'white';} addColor (dog); console.log (dog); / / {name: "puppy", age: 2, weight: 30, color: "white"}
As you can see, the addColor function modifies the properties of the dog object, which has a side effect.
Function addColor (dog) {let copyDog = Object.assign ({}, dog); copyDog.color = 'white'; return copyDog;}
In this way, the properties of the dog object are not modified, and the addColor function is a pure function.
2.4.3 return null
Null is relatively troublesome in processing and needs to be judged, resulting in additional code that should return an empty object, either an empty array, or throw an exception.
The difference between function and method
1) A function (function) is a piece of code that is called by name. It can pass some data (parameters) in for processing, and then return some data (return value), or no return value.
2) A method (method) is a javascript function called through an object. In other words, the method is also a function, only a relatively special function. He is associated with an object. Suppose that one function is fn and one object is obj, then you can define a method:
Obj.method = fn
Obj.method ()
3) the data of the function is explicitly passed
4) the data in the method is implicitly passed; the method is related to the object.
Thank you for your reading, the above is the content of "detailed explanation of JavaScript basic functions and methods". After the study of this article, I believe you have a deeper understanding of the detailed interpretation of JavaScript basic functions and methods, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.