


Detailed explanation of javascript function modules, cascading, application, and memory usage examples
A module is a function or object that provides an interface but hides state and implementation.
General form: a function that defines private variables and functions; uses closures to create privileged functions that can access private variables and functions; finally returns this privileged function, or saves them to a place where they can be accessed.
Function.prototype.method = function(name,func){ this.prototype[name] = func; return this; }; String.method("deentityify",function(){ var entity = { quot : '"', lt : '<', gt : '>' }; return function(){ return this.replace(/&([^&;]+);/g, function(a, b){ // 怎样知道a、b的值,了解正则表达式 var r = entity[b]; return typeof r === "string" ? r : a; }); }; }()); alert("<">".deentityify()); // 测试:<">
Note: The module mode is usually used in combination with the singleton mode. The singleton mode of JavaScript is an object created using object literals. The attribute value of the object can be a numerical value or a function, and the attribute value is in the object. No changes occur during the lifetime.
Cascade (chain operation)
For some methods that do not return a value, we return this instead of undefined, then we can start cascading (chain operation) to operate the object. As follows:
var $ = function(id){ var obj = document.getElementById(id); obj.setColor = function(color){ this.style.color = color; return this; }; obj.setBgColor = function(color){ this.style.backgroundColor = color; return this; // 返回this对象,启动级联 }; obj.setFontSize = function(size){ this.style.fontSize = size; return this; }; return obj; }; $("test").setColor("red") .setFontSize("30px") .setBgColor("blue"); // 改进后的代码: (function(id){ var _$ = function(id){ this.element = document.getElementById(id); }; _$.prototype = { setColor : function(color){ this.element.style.color = color; return this; }, setBgColor : function(color){ this.element.style.backgroundColor = color; return this; }, setFontSize : function(size){ this.element.style.fontSize = size; return this; } }; // 添加到window原型链中 window.$ = function(id){ return new _$(id); }; })(); $("test").setColor("red") .setFontSize("30px") .setBgColor("blue");
Apply
The so-called application is to combine the function with the parameters passed to it to generate a new function. For example: The following code defines an add() function, which can return a new function and pass the parameter value to the new function to achieve continuous addition operations.
// 第一种方式: var add = function(a){ return function(b){ return a + b; } }; alert(add(1)(2)); // 3 // 第二种方式:用arguments实现 var add = function(){ var arg = arguments; return function(){ var sum = 0; for(var i=0; i<arg.length; i++){ sum += arg[i]; } for(i=0; i<arguments.length; i++){ sum += arguments[i]; } return sum; } }; alert(add(1,2,3)(4,5,6)); // 21 // 第三种方式:通过一个套用方法(curry)实现 var add = function(){ var sum = 0; for(var i=0; i<arguments.length; i++){ sum += arguments[i]; } return sum; }; // 添加方法到Function的原型链上 Function.prototype.method = function(name, func){ this.prototype[name] = func; return this; }; // 套用方法 Function.method('curry', function(){ // 通过数组Array的slice方法,使得arguments也具有concat方法 var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function(){ return that.apply(null, args.concat(slice.apply(arguments))); }; }); alert(add.curry(1,2)(3,4)); // 10
Memory
Functions can use objects to remember the results of previous operations, thereby avoiding unnecessary operations. This optimization is called memorization.
var fibonacci = function(){ var mome = [0,1]; // 存放计算后的数据 var fib = function(n){ var result = mome[n]; // 如果不存在被计算过的数据,则直接计算。然后在将计算结果缓存 if(typeof result !== 'number'){ result = fib(n-1) + fib(n-2); mome[n] = result; } return result; }; return fib; }(); for(var i=0; i<=10; i++){ document.writeln("// " + i + ": " + fibonacci(i) + "<br/>"); } //========================== // 创建一个具有记忆的函数 //========================== var memoizer = function(memo, fundamental){ var shell = function(n){ var result = memo[n]; if(typeof result !== "number"){ result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; }; // 通过记忆函数memoizer完成斐波那契数列 var fibonacci = memoizer([0,1], function(shell, n){ return shell(n-1) + shell(n-2); }); // 通过记忆函数memoizer完成阶乘 var factorial = memoizer([1,1], function(shell, n){ return n * shell(n-1); }); for(var i=0; i<=15; i++){ document.writeln("// " + i + ": " + factorial(i) + "<br/>"); }
The above is the detailed content of Detailed explanation of javascript function modules, cascading, application, and memory usage examples. For more information, please follow other related articles on the PHP Chinese website!

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.

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.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools