APixel Visuals
APixel Visuals

Reputation: 1648

What's the point of JavaScript decorators?

I googled about JavaScript decorators but I'm not sure what the difference between calling a function using a decorator and calling a function normally is.

function myFunction(text) {
  console.log(text)
}

myFunction() vs @myFunction vs @myFunction()

I have a feeling I'm more than wrong here. Can someone explain?

Upvotes: 10

Views: 2606

Answers (4)

AJ Ashil
AJ Ashil

Reputation: 1

// Decorator function Example

const bioObject = { name: 'Ashil jayaraj'};
// To add new property on the bio object called 'Age': 26

const decoratorFn = (age) => {
  // Its a function returning new function
  return (bio) => {
    bio['age'] = age;
  }
  // This returned function just assign a key value pair on the object.
};

decoratorFn(26)(bioObject);
// onthe above line we are passing to function parameters
// 26 will be considered as Line no 12: age
// bioObject considered as Line no 14: obj (Argument)

console.log('bio object ', bioObject);`enter code here`

Upvotes: 0

zloctb
zloctb

Reputation: 11194

With decorators we can without extends. mutli inherits added some methods for Classes.

function withLoginStatus( DecoratorClass ) {
    return class extends DecoratorClass {
        constructor(...args ) {
            super(...args);
            this.isLoggedIn = false;
        }

        setLoggedIn() {
            console.log('setLogin!');
            this.isLoggedIn = true;
        }
    }
}


@withLoginStatus
class User {
    constructor(firstname, lastName) {
        this.firstname = firstname;
        this.lastName = lastName;
    }
    getFullName() {
        return `${this.firstname} ${this.lastName}`;
    }
}

Upvotes: 0

Jared Smith
Jared Smith

Reputation: 22050

Decorators are there to enable separation of concerns. Consider the following function:

function add(a, b) {
  return a + b;
}

Which is all well and dandy. But let's say that you want to add logging:

function add(a, b) {
  const sum = a + b;
  console.log(a, b, sum);
}

Now the function is longer and more complicated and conflates two things (summing and logging) that really don't have any relation. A better way to do it would be this:

function logs(f) {
  return function(...args) {
    const result = f(...args);
    console.log(args, result);
    return result;
  };
};

const addAndLog = logs(add);

And that's what a decorator is. What you're talking about (i.e. the JavaScript decorator proposal) is just a syntactic shortcut for the pattern above. Here logs is a decorator that adds a capability to the passed in function, the ability to log without having to complicate the function with a lot of extraneous code. The proposal is at the moment restricted to classes and methods, but I find it conceptually easier to explain with normal functions.

Upvotes: 6

Bertijn Pauwels
Bertijn Pauwels

Reputation: 585

Decorators are used to literally decorate a function.

Let's say you want to type your own decorator which can be used to see how much time a function needs to run. You could write a decorator @time() that does just that. When you are done, you can use this decorator before every function you want to track.

Decorators are used as high-order functions, mainly to have a functional composition of your code!

A nice example would be a @Component() decorator in Angular. Whilst using this decorator before your class, Angular knows it has to handle it as a component and does a couple of methods with it behind the scenes.

Upvotes: 3

Related Questions