将参数传递给JavaScript Object Getter

Joh*_*ard 15 javascript getter

var URIController = {
    get href() {
        return url.location.href;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有上面的对象结构.但URIController.href财产取决于另一个对象,url.

如果url全局定义,则URIController.href有效.但我想手动将url对象传递给hrefgetter.

var URIController = {
    get href(url) {
        return url.location.href;
    }
}
Run Code Online (Sandbox Code Playgroud)

更改了getter以接受url参数但是

URIController.href(url)
Run Code Online (Sandbox Code Playgroud)

因为href不是函数而抛出错误.

是否可以在javascript中将参数传递给getter?

sdg*_*uck 10

在您的示例中,您不是调用getter,而是调用对象上的函数href,该函数不存在.但该财产 href确实存在.

Getters不需要使用括号进行显式调用,因此不能接受参数.它们的调用是通过标准属性访问语法隐式的,例如URIController.href.

来自MDN的getter文档:

get语法将对象属性绑定到函数...

  • 它必须具有完全零参数

______

如果需要接受参数,请改用函数:

var URIController = {
    href: function (url) {
        return url.location.href;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用ES6对象函数的简写语法:

const URIController = {
    href (url) {
        return url.location.href;
    }
}
Run Code Online (Sandbox Code Playgroud)


Pat*_*ans 8

根据规范

生产 PropertyAssignment : get PropertyName ( ) { FunctionBody } 评估如下:

...

  1. 让闭包作为创建一个新的 Function 对象的结果,如 13.2 中所指定的,带有一个空的参数列表和由 FunctionBody 指定的主体。

所以你不能指定参数列表,尝试这样做会给你一个语法错误

var obj = {
    get href(param){}     
}
Run Code Online (Sandbox Code Playgroud)

如果你不想设置一个普通的函数,你可以做一些解决方法,比如在 getter 将读取的类实例/对象上设置一个属性。或者您可以在创建对象时使用闭包,然后您的 getter 可以从外部范围访问它。

作为实例/对象属性

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

obj.url = {location:{href:"http://stackoverflow.com"}};
console.log( obj.href );
Run Code Online (Sandbox Code Playgroud)

带外壳

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 );
Run Code Online (Sandbox Code Playgroud)


rud*_*eon 5

不,您不能使用“ setter”将参数传递给“ getter”。