var singletonPattern = (function() { var instance; functioninit() { // Singleton functionprivateMethod() { console.log('privateMethod'); } var privateVariable = 'this is private variable'; var privateRandomNumber = Math.random(); return { publicMethod: function() { console.log('publicMethod'); }, publicProperty: 'this is public property', getRandomNumber: function() { return privateRandomNumber; } }; } return { // Get the singleton instance if one exists // or create if it doesn't getInstance: function() { if (!instance) { instance = init(); } return instance; } }; })(); // Usage: var single = singletonPattern.getInstance();
var mediator = (function() { var topics = {}; var subscribe = function(topic, fn) { if (!topics[topic]) { topics[topic] = []; } topics[topic].push({ context: this, callback: fn }); returnthis; }; // publish/broadcast an event to the rest of the application var publish = function(topic) { var args; if (!topics[topic]) { returnfalse; } args = Array.prototype.slice.call(arguments, 1); for (var i = 0, l = topics[topic].length; i < l; i++) { var subscription = topics[topic][i]; subscription.callback.apply(subscription.content, args); } returnthis; }; return { publish: publish, subscribe: subscribe, installTo: function(obj) { obj.subscribe = subscribe; obj.publish = publish; } }; })();
原型模式
1 2 3 4 5 6 7 8 9 10 11 12
var myCar = { name: 'bmw', drive: function() { console.log('I am driving!'); }, panic: function() { console.log('wait, how do you stop this thing?'); } }; //Usages: var yourCar = Object.create(myCar); console.log(yourCar.name); //'bmw'
var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.gender = 'male'; }; var clark = new Person('Clark', 'kent');
var Superhero = function(firstName, lastName, powers) { Person.call(this.firstName, this.lastName); this.powers = powers; }; SuperHero.prototype = Object.create(Person.prototype); var superman = new Superhero('Clark', 'Kent', ['flight', 'heat-vision']); console.log(superman); //output personal attributes as well as power