Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
titledecorators.ts
linenumberstrue
function doSomething(name) 
{
	console.log('Hello, ' + name);
}
  
function loggingDecorator(wrapped) 
{
    return function(args) 
	{
    	console.log('Starting');
      	const result = wrapped.apply(this, [args]);
      	console.log('Finished');
      	return result;
    }
}

function loggingDecorator2(wrapped)
{
    return (args)=>
	{
      	console.log('Starting');
      	const result = wrapped.apply(this, [args]);
      	console.log('Finished');
      	return result;
    }
}
  
let loggingDecorator3 = (name, wrapped)=>
{
    return ()=>
	{
      console.log('Starting');
      const result = wrapped(name);
      console.log('Finished');
      return result;
    }
}
  
const wrapped = (name)=>{const fn=loggingDecorator(doSomething); fn(name);};
const wrapped2 = (name)=>{const fn=loggingDecorator2(doSomething);fn(name);};
const wrapped4 = (name)=>{const fn=loggingDecorator3(name, doSomething); fn();};

function readonly(target, name, descriptor) 
{
    descriptor.writable = false;
    console.log(name);
    return descriptor;
}

class Example 
{
    a() {}
    @readonly
    b() {}

    fooBar()
    {
        this.a();
        this.b();
    }
}
  
function  fooBar()
{
	doSomething('selvyn');

	wrapped('tomo');
    wrapped2('michelle');

    let x = loggingDecorator3('Alison', doSomething);
    x();

    wrapped4('tomo');

    const e = new Example();
}

Now look the three loggingDecorator functions we have defined.  Because TypeScript is strict, the code in the .js file won't compile.  So we have rewrite the our wrapped declarations, see lines 39-41.  We use the arrow function to call the loggingDecorator() functions.  Once the wrapped functions are declared we can use them as shown in lines 67-73.

Decorator Pattern Implementation

 So as can be from the code samples above in both pure JavaScript and TypeScript, the loggingDecorator() decorates the doSomething() function.