将参数传递给JavaScript对象获取器 [英] Passing Argument to JavaScript Object Getter

查看:44
本文介绍了将参数传递给JavaScript对象获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我具有上述对象结构.但是URIController.href属性取决于另一个对象url.

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

如果全局定义了url,则URIController.href起作用.但是我想手动将url对象传递给href getter.

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

将吸气剂更改为接受url参数,但

Changed the getter to accept url parameter but

URIController.href(url)

由于href不是函数而引发错误.

throws error because href is not a function.

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

Is it possible to pass arguments to getter in javascript?

推荐答案

在您的示例中,您不是在调用getter,而是在对象上调用了名为href的函数,该函数不存在.但是属性 href确实存在.

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.

字母不需要显式调用括号,因此不能接受参数.通过标准的属性访问语法(例如)隐式地调用了它们. URIController.href.

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.

获取有关MDN的文档:

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

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

  • 它的参数必须完全为零

______

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

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

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

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

Or using ES6 object function shorthand syntax:

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

这篇关于将参数传递给JavaScript对象获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆