Implementation method of val function overloading in jquery (with code)
The content of this article is about the implementation method of val function overloading in jquery (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The so-called overloading is a set of the same function name with different numbers of parameters. When using it, call a function name and pass in different parameters. It is decided according to the number of parameters you have. Use different functions! But we know that there is no overloading in js, because the function defined later will overwrite the previous function with the same name, but what should we do if we want to implement function overloading?
The first method:
This method is relatively simple. Give me an idea that everyone can definitely understand. It is to use the switch statement inside the function. According to the incoming parameters The number of different case statements is called, thereby achieving the effect of functional overloading.
This method is simple and crude
Second method:
function method(obj,name,fnc){ var old = obj[name]; console.log(old instanceof Function); obj[name] = function(){ console.log(arguments.length+" "+fnc.length); if(arguments.length === fnc.length){ return fnc.apply(this,arguments); }else if(typeof old === "function"){ return old.apply(this,arguments); } } } var people = { values:["Zhang san","Li si"] }; method(people,"find",function(){ console.log("无参数"); return this.values; }) method(people,"find",function(firstname){ console.log("一个参数"); var ret = []; for(var i = 0;i < this.values.length;i++){ if(this.values[i].indexOf(firstname) === 0){ ret.push(this.values[i]) } } return ret; }) method(people,"find",function(firstname,lastname){ console.log("两个参数"); var ret = []; for(var i = 0;i < this.values.length;i++){ if(this.values[i] == firstname + " " + lastname){ ret.push(this.values[i]) } } return ret; }) console.log(people.find()); console.log(people.find("Zhang"));
Implementation process: Let’s take a look at the above code. The most important thing is Definition of method method: The most important point in this method is this old, this old is really clever. Its function is equivalent to a pointer, pointing to the last called method function. This may be a bit unclear. According to the code, the parsing order of js is from top to bottom.
1. Parse the method (ignore the contents first)
2. method(people, "find", function() When this sentence is executed, it will go back to execute the method defined above , then the value of old is empty at this time, because you have not defined this function, so it is undefined at this time, and then continue to execute. This is when we defined obj[name] = function(), and then found out when js parsed The fnc function is returned, and more importantly, the fnc function also calls the variables in the method. This is not a closure, because the implementation of the fnc function is only implemented when it is called, so js thinks, I have finished executing this It can’t be deleted either. Otherwise, if you want to use the one outside, just keep it first (the call function is used here to change the this pointer inside the fnc function)
3. Okay, the first use of the method is over. , begins the second sentence, method(people,"find",function(firstname) Then when used this time, old = obj[name] needs to be executed again. What is old at this time? It is a function, because the previous statement It has been defined and not deleted, so my old this time actually points to the method defined last time. It acts like a pointer, pointing to the obj[name] defined last time. Then continue to parse, It’s a closure again, and it needs to be kept.
4. The third method call has started. Similarly, old points to the obj[name] defined last time. It is also a closure, and it needs to be kept. 5. At this point, there are actually three obj[name] in the memory, because the memory of the three methods has not been deleted. Is this realizing the coexistence of three functions? At the same time, they can also be used to old Isn’t the connection very clever?
6. When we call people.find(), we will first call the function defined when the method was called last time. If the number of parameters is the same, it is arguments.length === fnc.length Then just execute it, and there is no need to find other functions. If they are different, then you have to use old. return old.apply(this,arguments); old points to the definition when the last method was called. function, so we go to the last search. If found, continue to execute arguments.length === fnc.length. If not found, call old again and continue searching upward. As long as you have defined it, you will definitely be able to find it. Yes Let’s go!
Summary: Use the principle of closure to make three functions coexist in memory. old is equivalent to a pointer, pointing to the last defined function. Each time it is called, it is decided whether it needs to be searched.
Follow-up: After talking about the above, compare the understanding below, you will have a deeper understanding of prototypes and prototype chains
var array=[] addMethod(array,'sub0',function(){ return 0; }) addMethod(array,'sub0',function(prefix){ console.log("prefix===>",prefix); return prefix[0]; }) array.sub0([1,2,3,5]) //这里是array对象拥有了sub0这样的方法,而不是Array,addMethod是继承 // 区别于方法直接作用于原型上 //例子 String的 startsWith 实现 function addstartsWithToString(){ if (typeof String.prototype.startsWith1 != 'function' ) { String.prototype.startsWith1 = function(subString){ return this.slice(0,subString.length)==subString } } } addstartsWithToString(); '120000'.startsWith1('1')
Related recommendations:
Implementing functions in JavaScript Overloading and parameter default valuesJquery implements the Tab effect. The idea is js idea_jqueryHow to implement the overloading of JS functions _javascript skillsThe above is the detailed content of Implementation method of val function overloading in jquery (with code). For more information, please follow other related articles on the PHP Chinese website!

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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.