構(gòu)造函數(shù)模式
例子:
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayName = function(){
return this.name
}
var student = new Person('小明',20)
console.log(student)
混合模式
最典型的應(yīng)用就是原型的繼承
例子
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function() {
return this.name
}
function Student(name, age, score) {
Person.call(this, name, age)
this.score = score
}
function create(parentObj) {
function F() {}
F.prototype = parentObj
return new F()
}
//Student.prototype = Object.create(Person.prototype) 在chrome等現(xiàn)代瀏覽器上使用
Student.prototype = create(Person.prototype)
Student.prototype.constructor = Student
Student.prototype.sayScore = function() {
console.log(this.score)
}
var student = new Student('小明', 20, 100)
console.log(student)
模塊模式
例子
var Person = (function(){
var name = '小dong'
return{
changeName:function (newName){
name = newName
},
sayName:function(){
console.log(name)
}
}
})()
Person.changeName('xiaoming')
Person.sayName()
單例模式
例子:
var Person = (function(){
var instance
function init(){
//init可以自由定義
var name = '小明'
return{
sayName:function(){
console.log(name)
}
}
}
return{
createPerson:function(){
if(!instance){
instance = init()
}
return instance
}
}
})()
var obj1 = Person.createPerson()
var obj2 = Person.createPerson()
//兩個obj都指向了同一個對象
發(fā)布訂閱模式
var EventCenter = (function(){
var events = {}
/*
{
}
*/
function subscribe (event,handler){
events[event] = events[event] || []
events[event].push({
handler:handler
})
}
function publish(event,arguments){
if(!events[event]){
return
}
for(var i=0;i<events[event].length;i++){
events[event][i].handler(arguments)
}
}
return {
subscribe:subscribe,
publish:publish
}
})()
2.
var EventCenter = (function(){
var events = {}
/*
{
}
*/
function on (event,handler){
events[event] = events[event] || []
events[event].push({
handler:handler
})
}
function fire(event,arguments){
if(!events[event]){
return
}
for(var i=0;i<events[event].length;i++){
events[event][i].handler(arguments)
}
}
function delete(event){
if(!events[event]){
return
}
delete events[event]
}
return {
on:on,
fire:fire,
off:delete
}
})()