


How to use JavaScript functions? Introduction to the properties and methods of JavaScript functions
What is JavaScript function? Functions in JavaScript are actually objects, because each function is an instance of the Function constructor and has the properties and methods defined by the Function constructor. Let's take a closer look at the properties and methods of JavaScript functions.
The function name is actually a pointer to the function object. See the following code:
function sum(a,b) { return a + b; } // 相当于把sum的引用地址传递给sum2。 // 注意:不带圆括号的函数名是访问函数指针,而非调用函数 var sum2 = sum; sum2(1,2) // 3 sum = null; sum(2,3) // undefined // 将sum的内存回收,即sum的引用地址变了 sum2(2,3) //5 // 但sum2 还是指向原来的内存地址
The above code can illustrate the problem that the function name is actually a pointer to the function object. After understanding the above problems, we can conduct the following analysis:
1. No overloading
After understanding the above, reload Loading is equivalent to re-modifying the reference value of the function variable, so the previous one will be overwritten later, which is easy to understand.
2. Function promotion
#In fact, it is similar to variable promotion. It is the difference between declarative functions and expression-defined functions. It is very simple
3. Function as value
Because the function name itself is a variable, it can be passed as a value. Here is a good example, It is also a good programming idea, as follows:
function getSomeFunction(fn,arg) { return fn(arg); } function add(num) { return num + 10; } function getGreeting(name) { return `Hello ${name}`; } getSomeFunction(add,5) // 15 getSomeFunction(getGreeting,'andy') // Hello andy
You can also return another function from one function. For example, when we use some sorting methods or iteration methods of arrays, because what is passed in is a function variable as a parameter, we can write this parameter using the "external function return function" method. The advantage of this is, The returned function can pass in the parameters we "specifically want to specify" for calculation. For example, the parameter of the
// 规定利用哪个属性进行排序,如果不填则代表数组从大到小排序 function sortArgFuntion(compareProperty) { //compareProperty是上文中特定想要规定的参数 return function (val1, val2) { if (compareProperty === undefined) { // 如果排序的是数组的值,则用常规的方法 if (val1 > val2) { return 1; } else if (val1 val2[compareProperty]) { return 1; } else if (val1[compareProperty] <p>sort function is a function used to reorder the array. And when we take out the function parameters, we can write this function more intuitively and with higher reusability to achieve the effect we want. At the same time, you need to carefully study and understand the essence and uniqueness of the function return function</p><p><span style="font-size: 16px;"><strong>4. Internal properties of the function</strong></span></p><p>There are two special properties inside the function Variables</p>
arguments
this
arguments
is an array-like object. What is an array-like object? Array-style access can be performed through serial numbers (such as obj[1]), and there is a length attribute (if you do not define the length attribute of the object, it does not have length). The class array only has the index value and length, and does not have various methods of the array, so If you want to call an array method like an array, you need to use Array.prototype.method.call
to implement
this
this is very JavaScript A confusing and complex point of knowledge, what it represents depends entirely on the calling location, I will but list a summary this. e.g:
window.color = 'red'; var o = {color:"blue"}; function sayColor() { console.log(this.color) } sayColor(); // red 因为调用位置是全局 o.sayColor = sayColor; o.sayColor(); // blue 因为调用位置是o的对象里
We need to know from the above example that the function name is just a pointer. Although the execution environment is different, the global sayColor() and the o.sayColor() in the function point to the same function.
caller
Newly added in es5, it returns the calling environment of the current function (must be a function, not an object). If the calling environment is global, null is returned. There are two usages, one is the function name plus caller, the other is arguments.callee.caller
function outer() { console.log(outer.caller); //null inner(); }; function inner() { console.log(inner.caller); // outer里的代码 }
5. Function attributes and methods
Because functions are also objects, they also have properties and methods; there are two properties in the function: length and prototype. Length refers to the number of parameters passed in. function add(num1,num2) {} console. log(add.length) // 2
propertype
For reference types, propertype is the real place where all instance methods are saved. When creating custom reference types and implementing inheritance, its role and key (how many key points are not yet understood, especially the word inheritance:)) In es5, property type is not enumerable, so it cannot be traversed .
apply() and call()
Two parameters, the first parameter is the scope in which to run, and the second parameter apply is the incoming Array Or the arguments object, call passes in each value, and the rest are exactly the same. This is one of the examples to illustrate the role of apply and call:
var color = "red"; var o = {color:"blue"}; function sayColor() { alert(this.color) } sayColor(); // red sayColor.call(this); // red sayColor.call(window); // red sayColor.call(o); // blue
If we don’t use call, we need to do this:
var color = "red"; var o = {color:"blue"}; function sayColor() { alert(this.color) } o.sayColor = sayColor; o.sayColor(); //blue
So the comparison can be seen at a glance. The biggest role of call is to achieve Decoupling objects and methods
bind method
The bind method is used to construct an instance of a function, and its this object points to the scope specified by bind.
For example:
var color = "red"; var obj = {color:"blue"} function sayColor() { console.log(this.color); } var bindSayColor = sayColor.bind(obj); bindSayColor(); // blue
Recommended related articles:
Javascript ordinary functions and constructs The difference between functions
Detailed explanation of function declaration and call in JavaScript
The above is the detailed content of How to use JavaScript functions? Introduction to the properties and methods of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.