DEV Community

Discussion on: Wrap a JS function transparently

Collapse
 
wadecodez profile image
Wade Zimmerman • Edited

My original post was a joke because 'this' is a context sensitive word in English and JavaScript.

Anyways, after thinking about this, the better questions are: When should I modify the scope vs passing a parameter? When should I use a decorator vs a callback? What is the best pattern for attaching behavior?

IMO this should not be used outside of classes since arrow functions exist and decorators should probably be preferred over callbacks for comparability purposes.

Unfortunately you cannot really see the benefit of decorators unless you use TypeScript.

Both snippets do the same thing. A function is evaluated if some path matches the request path. It all comes down to how/when the code should be accessible.

Although in typescript, you technically do not have to invoke a function, you have more control over data, and you can reuse the wrapper.

// Plain JavaScript

function Request () {
    this.path = "/users"
}

function Route () {}

Route.get = function (path) {
    return function(handler) {
    const req = new Request()
    return path === req.path ? handler.apply({req}, [req]) : null
  }
}

Route.get('/users')(function (req) {
    console.log(this, req)
})
Enter fullscreen mode Exit fullscreen mode
//TypeScript

class Request {
    path = "/users"
}

class Route {
    static get(path:string) {
        return function(target:any, propertyKey: string, descriptor: PropertyDescriptor) {
                const req = new Request()
                return path === req.path ? target[propertyKey].apply({req}, [req]) : null;
        }
    }
}

class Controller {
    @Route.get('/users')
    @Route.get('/users/all')
    public getUsers (req: Request) {
        console.log("hello users", this, req)
    }
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
smlka profile image
Andrey Smolko

Thanks for your comment, appreciate it!
Actually the topic of my post is also valid for decorators syntax as anyway a decorator is a wrapper function and does not pass this inside a decorated function.