工厂方法模式(安全的工厂方法)

场景:页面中创建不同功能的按钮(添加、删除、提交、确认...)

var Factory = function(type,content){
    if(this instanceof Factory){
        var s = new this[type](content);
        return s;
    }else{
        return new Factory(type,content);
    }
}
Factory.prototype = {
    add:function(contetn){
        // add button
    },
    del:function(content){
        // del button
    },
    confirm:function(content){
        (function(content){
            var btn = document.createElement('button');
            btn.innerHTML = content;
            btn.style.color = red;
            document.getElementById('container').appendChild(btn);
        })(content)
    }
}
var data = [
    {type:'add',content:'添加'},
    {type:'del',content:'删除'},
    {type:'confirm',content:'确认'}
];

for(var i = 3; i >= 0; i--){
    Factory(data[i],type,data[i].content);
}

 

posted @ 2019-01-05 21:06  佳琪欧尼  阅读(249)  评论(0编辑  收藏  举报