简体   繁体   中英

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.

Any idea how this could be done (if at all)?

You can use Object.defineProperty() to do this

 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. In a web-browser the Window object is the global object, so this:

<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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM