Home  >  Article  >  Web Front-end  >  Singleton pattern in js

Singleton pattern in js

不言
不言Original
2018-04-10 13:55:531411browse

The content shared with you in this article is about the singleton mode in js, which has certain reference value. Friends in need can refer to it


js Single Example pattern


As the name suggests: Only one instance object can be generated

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>js_singleton_pattern_edition02(improvement)</title>
    <style>
        p {            color: red;        }
    </style></head><body>
    <button id="login">login</button>
    <script>
        // 单例模式实现: 通过一个 标志来判定 实例是否只生成了一次
        // 依旧是通过闭包保存一个 非全局变量 result 
        var getSingle = function (fn) {
            var result; // 这里用一个 flag 就可以了 , 来标志是否是单例
            return function () {
                return result || (result = fn.apply(this, arguments))
            };
        }        // 生成 单例函数
        var createp = getSingle(function (){
            var p = document.createElement(&#39;p&#39;);
            p.innerHTML = "我是登录悬浮框";
            p.style.display = &#39;none&#39;;
            document.body.appendChild(p);            return p;
        });

        document.getElementById(&#39;login&#39;).onclick = function () {
            var op = createp();
            op.style.display = &#39;block&#39;;
        }        // 将上述管理单例的逻辑抽离出来
        // 创建实例对象的职业 和 管理单例职责 相互独立
        var getSingle = function (fn) {
            var result;            return function () {
                return result || (result = fn.apply(this.arguments))
            }
        }    </script></body></html>

           

Related recommendations:

js singleton mode creation pop-up window instance sharing

js singleton mode detailed explanation example_basic knowledge

The above is the detailed content of Singleton pattern in js. 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
Previous article:Cross-domain issues in jsNext article:Cross-domain issues in js