构造函数模式
例子:
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)
混合模式
最典型的应用就是原型的继承
例子
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等现代浏览器上使用
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都指向了同一个对象
发布订阅模式
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
}
})()
网友评论