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

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

伊谢尔伦
伊谢尔伦Original
2017-07-25 11:22:331681browse

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()); // 测试:<">

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(&#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

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/>");
}

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:
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