Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  196] [ 5]  / answers: 1 / hits: 36058  / 8 Years ago, sat, may 21, 2016, 12:00:00
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?


More From » getter

 Answers
5

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;
}
}

[#62076] Thursday, May 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kelsy

Total Points: 486
Total Questions: 86
Total Answers: 76

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
kelsy questions
Tue, Oct 19, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
Fri, Jan 10, 20, 00:00, 4 Years ago
;