[英]JavaScript variable that behaves like a function
Is it possible to create a variable that is linked to a function and executes this function every time the variable is being read?是否可以创建一个链接到函数并在每次读取该变量时执行该函数的变量? A use case would be updated language translations when the call to a certain translation already happened (returning a translation string which might change in future).
当对某个翻译的调用已经发生时,用例将更新语言翻译(返回一个将来可能会更改的翻译字符串)。 This is kind of similar to
get
ter methods of a class, but without actually defining a class.这样的相似,
get
一类的方法之三,但没有实际定义的类。
Any idea how this could be done (if at all)?知道如何做到这一点(如果有的话)?
You can use Object.defineProperty()
to do this您可以使用
Object.defineProperty()
来做到这一点
Object.defineProperty(this, 'prop', { // adding to whatever "this" context is get: () => Math.random() }) console.info('prop get #1', prop) console.info('prop get #2', prop)
One option is to take advantage of the fact the global
object can have properties defined on it that are implicitly in-scope.一种选择是利用
global
对象可以在其上定义隐式在范围内的属性这一事实。 In a web-browser the Window
object is the global
object, so this:在 Web 浏览器中,
Window
对象是global
对象,因此:
<script>
var foo = 123;
function bar() { console.log( foo ) };
bar();
</script>
Is the same as this:是不是和这个一样:
<script>
document.window.foo = 123;
function bar() { console.log( foo ) };
bar();
</script>
Is (more-or-less) the same as this:是否(或多或少)与此相同:
<script>
Object.defineProperty( window, "foo", { value: 123 } );
function bar() { console.log( foo ) };
bar();
</script>
So we can abuse Object.defineProperty
to get the effect you want, with the caveat that it won't work inside JavaScript scopes where global
's properties are not accessible.因此,我们可以滥用
Object.defineProperty
来获得您想要的效果,但需要注意的是,它不能在global
属性不可访问的 JavaScript 范围内工作。
<script>
function createMagicVariable( name, func ) {
var propDef = {
get: func
};
Object.defineProperty( window, name, propDef );
}
</script>
Used like so:像这样使用:
<script>
function getRandom() { return Math.random(); }
createMagicVariable( 'foo', getRandom );
console.log( foo );
console.log( foo );
console.log( foo );
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.