Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Adding an Audit Without Changing the Call

Adding an Audit Without Changing the Call

In this lesson, you port a Python decorator to a JavaScript wrapper that you apply by hand. The translation desk wants an audit line for every quote, without changing how quote is called or what it returns.

In Python, @with_audit(audit) decorates the quote method. Its inner function, wrapped, takes *args and **kwargs, passes them on, appends a line, and returns the result. Because quote is a method, self is the first argument, so the words are args[1]:

Language: Python
from functools import wraps

def with_audit(entries):
    def decorate(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            result = fn(*args, **kwargs)
            line = f"quoted {args[1]} words: {result}p"
            entries.append(line)
            return result
        return wrapped
    return decorate

audit = []

class Desk:
    rate_pence = 12

    @with_audit(audit)
    def quote(self, words):
        return words * self.rate_pence

desk = Desk()
print(desk.quote(400))
print(audit)

The @ line is shorthand for quote = with_audit(audit)(quote). In JavaScript, you write that replacement out: pass the method to withAudit() with the audit array, and assign the result back to desk.quote in place of the method. Unlike the @ line, it’s an ordinary assignment that runs after the desk exists. The call stays the same:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this lesson, you’ll port a Python decorator to a wrapper you apply by hand. The translation desk wants an audit line for each quote, without changing how quote is called or what it returns.

00:12 In Python, @with_audit(audit) decorates the quote method. Its inner function takes *args and **kwargs, passes them on, appends a line, and returns the result.

00:24 The script prints 4800 and the audit line.

00:29 Because quote is a method, self is the first argument, so the words are the second.

00:36 In the JavaScript port, the desk is an object literal, and quote reads the rate from this, the object before the dot. Python’s @ line is shorthand for quote = with_audit(audit)(quote).

00:50 In JavaScript, you write that replacement out: pass the method to withAudit() with the audit array, and assign the result back to desk.quote in place of the method.

01:01 Unlike the @ line, it’s an ordinary assignment that runs after the desk exists. The call stays the same.

01:09 Then write the withAudit() function itself. It takes the method and the array in one call: Python needs its extra layer only because the @ line wants a decorator back.

01:21 It returns a function expression, the function keyword used as a value, with no name. It’s a regular function, which matters for this.

01:30 Its rest parameter collects the arguments into an array, as *args does into a tuple. JavaScript has no keyword arguments, so **kwargs has no match here.

01:41 And like wrapped, it’s a closure that keeps the method and the array.

01:47 Python’s args included self. So when desk.quote(400) runs, what does this wrapper’s args hold? Your turn: pause the video and predict.

02:03 Only the words: one item, 400.

02:07 The receiver travels separately, as this, so unlike in Python, the kind of function you return matters. Inside, fn.apply() calls the original method with the wrapper’s own this and the args array.

02:21 In desk.quote(400), the wrapper is the method being called, so its this is the desk, and apply() hands it on. A line-by-line port would spread the arguments into a plain call, with no receiver, so this.ratePence would have nothing to read.

02:39 The original method reads the rate from the desk, and the wrapper saves its answer as result. It builds the audit line from the words, now args[0], not args[1], and the result.

02:52 Then it pushes the line onto the array and returns the saved result. Run both files, and JavaScript logs 4800, as Python does. The audit holds one line: quoted 400 words, 4800 pence.

03:09 Same arguments, same receiver, same result, and one line added.

03:16 That this is why the returned function isn’t an arrow. A regular function gets its this from each call, here the desk. An arrow has none of its own.

03:27 It looks outward to the body of withAudit(), the same lookup that left an arrow formatter without its desk. And withAudit() was called plainly, so its this is undefined.

03:38 An arrow wrapper would pass that on, and reading the rate would throw a TypeError instead.

03:45 Python’s @wraps copies the method’s name, docstring and signature details onto wrapped. In JavaScript, desk.quote is now a new function, and nothing copies the method’s name onto it.

03:58 Callers find it by the name you write: the quote property. Stacked decorators are function composition, and explicit wrappers nest the same way: the innermost is applied first, so on each call the outermost runs first.

04:13 And errors pass through. If the method throws, nothing is pushed, and the caller gets the same error, unless the wrapper catches it on purpose.

04:23 So a transparent wrapper forwards the same arguments, receiver and result, and adds only its audit. Return a regular function, and pass its this and its arguments on with apply(), unchanged.

04:36 Then apply the wrapper yourself, with an assignment. Next up is the text lesson Remembering a Successful Call Even When It Returns Zero. There, you’ll write a wrapper that changes behavior on purpose: it runs the desk’s setup once, and keeps returning that result, even when it’s zero.

Become a Member to join the conversation.