JS 디자인 모드(6가지 유형)

2779 단어

1. 구조 함수 모드: 새 대상을 되돌려줍니다


constructor new를 통해 실현
function Person(name,age){
    this.name = name;
    this.age = age;
}
Person.prototype.sayName = function(){
    return this.name;
}

var student = new Person("YQY",22);

2. 플랜트 모드: 새 객체 반환


factory
function createPerson(name){
    var person= {
        name: name,
        sayName:function(){
            console.log(this.name);
        }
    };
    return person;
}
// 
createPerson("YQY").sayName() // YQY
createPerson("xiaoming").sayName()  //xiaoming
// 
var t = createPerson("YQY").sayName()
t()   //undefined    
// createPerson sayName this window


3. 단일 모드


singleton
var People = (function(){
    var instance;
    function init(name){
        return{
            name: name
        };
    }

    return{
        createPeople : function(name){
            if(!instance){
                instance = init(name);
            }
            return instance
        }
    }
}());

People.createPeople("YQY") //{"name" :"YQY"}
People.createPeople("xiaoming") //{"name" :"YQY"}


4. 블렌드 모드


mix in 상속
var Person = function(name,age){
    this.name = name;
    this.age = age;
}

Person.prototype.sayName = function(){
    console.log(this.name);
}

var Student = function(name,age,score){
    Person.call(this,name,age);
    this.score = score;
};

//Student.prototype = Object.create(Person.prototype)
Student.prototype = create(Person.prototype);

function create(parentObj){
    function F(){}
    F.prototype = parentObj;
    return new F();
};

Student.prototype.sayScore = function(){
    console.log(this.score);
}

var student = new Student("YQY",22,95);

5. 모듈 모드: 클립을 통해 하나의 모듈을 실현


module
var Person = (function(){
    var name = "YQY";
    function sayName(){
        console.log(name);
    }
    return {
        name:name,
        sayName:sayName
    }
})()

Person //{name:name,sayName:sayName}

6. 게시 모드에 가입


publish/subscribe
var EventCenter = (function(){
    var events = {};
    function on(evt,handler){
        events[evt] = events[evt] || [];
        events[evt].push({
            handler:handler
        });
    }

    function fire(evt,args){
        if(!events[evt]){
            return;
        }
        for(var i = 0; i < events[evt].length; i++){
            events[evt][i].handler(args);
        }
    }

    function off(name){
        delete events[name]
    }

    return{
        on:on,
        off:off,
        fire:fire
    }
})();

좋은 웹페이지 즐겨찾기