Passing Argument to JavaScript Object Getter

前端 未结 3 737
天涯浪人
天涯浪人 2021-02-02 09:53
var URIController = {
    get href() {
        return url.location.href;
    }
}

I have above object structure. But URIController.href pro

3条回答
  •  春和景丽
    2021-02-02 10:33

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

提交回复
热议问题