1. define

To dynamically add some additional responsibilities to an object without affecting other objects derived from that class. Is a “pay-as-you-go” method that dynamically adds responsibilities to an object while the program is running without changing the object itself. The core

Is to dynamically add behavior to an object, through multiple wraps, can form a decorative chain

  1. implementation

The simplest decorator is to override the properties of an object


var A = {
    score: 10
};
A.score = 'Score:' + A.score;
Copy the code

You can use traditional object-oriented methods to implement decorations and add skills

function Person() {}

Person.prototype.skill = function() {
    console.log('mathematics');
};

// Can also play music
function MusicDecorator(person) {
    this.person = person;
}

MusicDecorator.prototype.skill = function() {
    this.person.skill();
    console.log('music');
};

// You can run
function RunDecorator(person) {
    this.person = person;
}

RunDecorator.prototype.skill = function() {
    this.person.skill();
    console.log('running');
};

var person = new Person();

// Decorate it
var person1 = new MusicDecorator(person);
person1 = new RunDecorator(person1);

person.skill(); / / math
person1.skill(); // Math music running
Copy the code

In JS, functions are first-class objects, so we can also use more generic decorator functions

// decorator to execute another function before the current one
function decorateFn(fn,beforeFn){
    return function(){
        let ret=beforeFn.apply(this.arguments)
        // In the previous function, the current function does not need to be executed
        if(ret! = =false){
            fn.apply(this.arguments)}}}function skill() {
    console.log('mathematics');
}
function skillMusic() {
    console.log('music');
}
function skillRun() {
    console.log('running');
}
let decorateSkill=decorateFn(skill,skillMusic)
decorateSkill=decorateFn(decorateSkill,skillRun)
decorateSkill()
// Running, music, math
Copy the code