简体   繁体   中英

Javascript function decorator design pattern

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.

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 + '.');
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM