构造函数模式
function People(name,age) {
this.name=name
this.age=age
}
People.prototype.say=function(argument) {
console.log(this.name+this.age)
}
new People('小明','27')
模块模式
var module=(function() {
var name='小明'
function sayName() {
console.log(name)
}
return{
name:name,
sayName:sayName
}
}())
工厂模式
function factory(args) {
var people={
name:args.name
}
people.say=function() {
console.log(this.name)
}
return people
}
var p1=factory({name:'小明'})
混合模式
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.constructor=Student
Student.prototype.sayScore = function(){
console.log(this.score);
}
var student = new Student("小明", 28, 99);
console.log(student);
单例模式
var people=(function () {
var instance
function init(args) {
return args
}
return {
createPeople:function(name) {
if (!instance) {
instance=init(name)
}
return instance
}
}
}())
var student=people.createPeople('小明')
people.createPeople('xxx')
订阅发布模式
var Event=(function() {
var events={} ; //{change:[{handler:function(){}},{handler:function(){}}]}
var on=function(evt,handler) {
events[evt]=events[evt] || []
events[evt].push({
handler:handler
})
};
var fire=function(evt,args) {
if (!events[evt]) { return }
for (var i = 0; i < events[evt].length; i++) {
events[evt][i].handler(args)
}
};
var off=function (evt) {
if (!events[evt]) { return }
delete events[evt]
}
return {
on:on,
fire:fire,
off:off
}
}())
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '小明');
Event.off('change');
网友评论