设计模式 javascipt

Posted halo-world

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式 javascipt相关的知识,希望对你有一定的参考价值。


//1. ES5 闭包实现单例模式

        let singleton = (function(){
            let instance = null;

            return function(name){
                this.name = name;

                instance = instance? instance : this;
                return instance;
            }
        })();

        singleton.prototype.getName = function(){
            return this.name;
        }
        let w = new singleton("hello");
        console.log(w.getName());

        let m = new singleton("nihao")
        console.log(m.getName());


// 2. ES6 实现单例模式
   
     class singleton {
         constructor(name){
             this.name = name;
         }
         
         static getInstance(name){
             if(!this.instance){
                 this.instance = new singleton(name);
             }

             return this.instance;
         }
      }

      let w = singleton.getInstance("hello");
      console.log(w.name);

      let m = singleton.getInstance("nihao")
      console.log(m.name);



以上是关于设计模式 javascipt的主要内容,如果未能解决你的问题,请参考以下文章

JavaScipt设计模式初探-代理模式 保护代理

JavaScipt设计模式初探-代理模式 虚拟代理

javascipt继承机制(from阮一峰)

认识JavaScipt

JavaScript---认识JavaScipt

JavaScipt 中的事件循环机制,以及微任务 和宏任务的概念