


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) { return -1; } else { return 0; } } else { // 如果排序的是对象的属性则用该方法 if (val1[compareProperty] > val2[compareProperty]) { return 1; } else if (val1[compareProperty] < val2[compareProperty]) { return -1; } else { return 0; } } } } var data = [{ name: 'andy', age: 25 }, { name: 'Nf', age: 29 }] data.sort(sortArgFuntion('name'))
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
4. Internal properties of the function
There are two special properties inside the function Variables
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!

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

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





How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
