写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例
- 构造函数模式
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function() {
return this.name
}
var student = new Person("jack", 30)
- 混合模式
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 stu1 = new Student("jack", 18, 60)
- 模块模式
var Person = (function() {
var name = "jack"
function sayName() {
console.log(name)
}
return {
name: name,
sayName: sayName
}
}())
Person
- 工厂模式
function createPerson(name) {
var person = {
name: name
}
person.sayName = function() {
console.log(this.name)
}
return person
}
createPerson("mary").sayName()
或
function createPerson(name) {
var person = {
name: name,
sayName: function() {
console.log(this.name)
}
}
return person
}
createPerson("mary").sayName()
- 单例模式
var People = (function(){
var instance
function init(name) {
return {
name: name
}
}
return {
createPeople: function(name) {
if(!instance) {
instance = init(name)
}
return instance
}
}
}())
console.log(People.createPeople("jack"))
console.log(People.createPeople("mary"))
- 发布订阅模式
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(i=0; i<events[evt].length; i++) {
events[evt][i].handler(args)
}
}
function off(evt) {
delete events[evt]
}
return {
on: on,
fire: fire,
off: off
}
}())
EventCenter.on("hello", function(){console.log("test")})
EventCenter.fire("hello")
EventCenter.fire("hella")
使用发布订阅模式写一个事件管理器
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(i=0; i<events[evt].length; i++){
events[evt][i].handler(args)
}
}
function off(evt) {
delete events[evt]
}
return {
on: on,
fire: fire,
off: off
}
}())
var Event = EventCenter
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('change');
Event.fire('change', '饥人谷');
网友评论