Passing Argument to JavaScript Object Getter

John Bernard picture John Bernard · May 21, 2016 · Viewed 22.2k times · Source
var URIController = {
    get href() {
        return url.location.href;
    }
}

I have above object structure. But URIController.href property depends on another object, url.

If the url is defined globally, URIController.href works. But I want to pass url object to href getter manually.

var URIController = {
    get href(url) {
        return url.location.href;
    }
}

Changed the getter to accept url parameter but

URIController.href(url)

throws error because href is not a function.

Is it possible to pass arguments to getter in javascript?

Answer

sdgluck picture sdgluck · May 21, 2016

In your example you are not invoking the getter, but rather a function on the object called href, which doesn't exist. But the property href does exist.

Getters do not require explicit invocation with parentheses and cannot therefore accept arguments. Their invocation is implicit via standard property access syntax, e.g. URIController.href.

From getter documentation on MDN:

The get syntax binds an object property to a function...

  • It must have exactly zero parameters

______

If you need to accept arguments, use a function instead:

var URIController = {
    href: function (url) {
        return url.location.href;
    }
}

Or using ES6 object function shorthand syntax:

const URIController = {
    href (url) {
        return url.location.href;
    }
}