JSFiddle - React, Tailwind, and code Playground

by Aubrey Taylor

HTML

<h1>Decorator Example</h1>
<p class="foo"></p>
<p class="foo-decorated"></p>
<p class="qoo"></p>

CSS

h1{
 font-family: sans-serif;
 font-weight:bold;
 font-size:25px;
 padding-bottom:15px;
 padding-left:10px;
 padding-top:10px;
}
p{
 font-family: Courier, sans-serif; 
 font-size: 13px;
 padding-left:10px;                
}

JavaScript

function foo(){

    function print(){
        return 'foo';
    }
    
    return {'print': print};
}

function bar(foo){
    var output = foo.print();        

    foo.print = function(){
       return output + ' bar';     
    };
    
    return foo;
}

// create two instances of foo
var f = foo();
var q = foo();

// test foo.print
$('.foo').html('{ f } undecorated print &rarr; ' + f.print());
    
// decorate foo.print with bar
f = bar(f);
$('.foo-decorated').html('{ f } decorated print &rarr; ' + f.print());
    
// show that original other instance still uses non-decorated
$('.qoo').html('{ q } undecorated print &rarr; ' + q.print());