Home Web Front-end JS Tutorial Detailed explanation of javascript function modules, cascading, application, and memory usage examples

Detailed explanation of javascript function modules, cascading, application, and memory usage examples

Jul 25, 2017 am 11:22 AM
javascript js Apply

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   : &#39;<&#39;,
        gt   : &#39;>&#39;
    };
    return function(){
        return this.replace(/&([^&;]+);/g, function(a, b){ // 怎样知道a、b的值,了解正则表达式
            var r = entity[b];
            return typeof r === "string" ? r : a;
        });
    };
}());
alert("<">".deentityify()); // 测试:<">
Copy after login

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");
Copy after login

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(&#39;curry&#39;, 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
Copy after login

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 !== &#39;number&#39;){
            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/>");
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

See all articles