Skip to content Skip to sidebar Skip to footer

Javascript - Can We Have Self Invoking Function Modules Assigned To Variables

Can variable be assigned self invoking function module so that the variable reference would trigger calling the function without the () operator. I want the variable to have the la

Solution 1:

This behaviour can be achieved via a getter, using Object.defineProperty, for example:

// Add a `somemethod` property to `window`Object.defineProperty(window, 'somemethod', {
    get: function() {
        returnMath.random();
    }
});
console.log(window.somemethod);
console.log(window.somemethod); // Different value

Solution 2:

No, but you can use getters and setters of object properties: https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

Post a Comment for "Javascript - Can We Have Self Invoking Function Modules Assigned To Variables"