Reputation: 866
Is there any design pattern I can implement a decorator in Javascript?
Let's say I have a user
object, with a is_authenticated
property.
var user = {
is_authenticated: true,
name: 'Peter Parker'
}
In Python I would create a decorator to return the property is_authenticated
and only run the function commands if that decorator returned truly, like this:
function userIsAuthenticated() {
return user.is_authenticated;
}
@userIsAuthenticated
function say(message) {
console.log(message + '\nSays ' user.name + '.');
}
Is Javascript I have to check if the user is authenticated before running anything inside the function.
function say(message) {
if (user.is_authenticated) {
console.log(message + '\nSays ' user.name + '.');
}
}
How can I do any decorator-like is Js?
I thought about binding
the function in its creation
function say(message) {
this && (function(){
console.log(message + '\nSays ' user.name + '.');
}());
}.bind(user.is_authenticated);
But that way you lose the instance (this
is now true/false) and also more characters.
Upvotes: 1
Views: 739
Reputation: 859
Well in ES2016 you can use the same decorator pattern that python does. I've created a module that let you easily wrap your original code with your own.
https://github.com/cmartin81/decorator-wrap
Upvotes: 0
Reputation: 664297
Just wrap it, and let is_authentificated
return a new function:
function userIsAuthenticated(fn) {
return function() {
if (user.is_authenticated)
return fn.apply(this, arguments);
};
}
You can decorate arbitrary functions with it:
var say = userIsAuthenticated(function say(message) {
console.log(message + '\nSays ' + user.name + '.');
});
Upvotes: 1