Created
February 8, 2015 08:50
-
-
Save laispace/8956668723a0422f90e1 to your computer and use it in GitHub Desktop.
设计模式-装饰者模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pattern-decorator.js | |
// ===== 1. let instance has new functions ===== | |
function Person (name, age) { | |
this.name = name; | |
this.age = age; | |
} | |
Person.prototype.say = function (something) { | |
console.log(this.name, 'says: ', something); | |
}; | |
// now we new a person | |
var person1 = new Person('xiaolai-1', 18); | |
// let me say hi | |
person1.say('hi'); | |
// then we new another person | |
var person2 = new Person('xiaolai-2', 19); | |
// let me say hello | |
person2.say('hello'); | |
// and le me have the ability to run | |
person2.run = function (distance) { | |
console.log(this.name, 'runs: ', distance, 'miles'); | |
}; | |
// NOTE that person2 can run but person1 can not. | |
// ===== 2. let instance has adding propertity ===== | |
var person3 = new Person('xiaolai-3', 20); | |
function AddAge5 (person) { | |
person.age += 5; | |
} | |
function AddAge10 (person) { | |
person.age += 10; | |
} | |
function AddAge20 (person) { | |
person.age += 20; | |
} | |
// now let my age inscrease! | |
AddAge5(person3); | |
console.log(person3.age); | |
AddAge10(person3); | |
console.log(person3.age); | |
AddAge20(person3); | |
console.log(person3.age); | |
jquery 中的 $.extend 和
underscore 中的 _.extend 可以理解为装饰者模式的一种实践
var defaults = {nage}
var options = {};
var settings = {};
settings = $.extend({}, defaults, options);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
装饰者模式可以简单理解为对实例进行添加属性或方法的模式