Versions Compared

Key

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

...

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

function loggingDecorator2(wrapped)
{
    return ()=>
	{
    	console.log('Starting');
      	const result = wrapped.apply(this, arguments);
      	console.log('Finished');
      	return result;
    }
}
  
const wrapped = loggingDecorator(doSomething);
const wrapped2 = loggingDecorator2( doSomething );

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

class Example 
{
    a() {}
	// an attempt assign a decorator, does not work in regulator ES3 and ES5, you will get an error on the b(){} declaration
    @readonly
    b() {}

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

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

In regular JavaScript JavaScript lines 56 and 57 perform some very clever magic.  Lines 28 and 29 declare two variable that are actually anonymous functions.  Yes that seems crazy because lines 28/29 look like they are getting a reference to a function, but that's not the case, they are receiving the result of loggingDecorator() and loggingDecorator2() respectively (they're just regular function calls - if we had written const wrapped = loggingDecorator; then that would be a function reference). The type returned from both functions is an anonymous function, so it makes sense.

So JavaSciprt being JavaScipt allows you to declare a function with no parameters, then call it with parameters that can be accessed within the function through the arguments variable that is an array.  Hence lines 11 and 22 work, and the calls at 56 and 57 work.

TypeScript

I then develop a version of the code in typescript which clearly allowed me to use the decorator syntax in the file but not in a browser.  The file extension is .ts

...