Passing Argument to JavaScript Object Getter

对着背影说爱祢 提交于 2020-01-22 09:28:21

问题


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?


回答1:


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



回答2:


No, you can't pass an argument to a " getter " use a " setter " rather.




回答3:


As per the spec

The production PropertyAssignment : get PropertyName ( ) { FunctionBody } is evaluated as follows:

...

  1. Let closure be the result of creating a new Function object as specified in 13.2 with an empty parameter list and body specified by FunctionBody.

So you cannot specify a parameter list, attempting to do so will give you a syntax error

var obj = {
    get href(param){}     
}

If you do not want to setup a normal function you could do a couple workarounds like set a property on the class instance/object that the getter would then read. Or you could use a closure upon creating your object then your getter could access it from the outer scope.

As an instance/object property

var obj = {
    url:null,
    get href(){
       return this.url ? this.url.location.href : "";
    }
}

obj.url = {location:{href:"http://stackoverflow.com"}};
console.log( obj.href );

With an enclosure

function URIController(url){
    //You could also use `Object.defineProperty` to 
    //create the getter on a existing object
    return {
       get href(){
          return url.location.href;
       }
    }
}
var obj = URIController({location:{href:"http://stackoverflow.com"}});
console.log( obj.href );


来源:https://stackoverflow.com/questions/37366181/passing-argument-to-javascript-object-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!