Ways to guarantee that a function is executed only once within an object notation

Although there are numerous techniques available on Stack Overflow to ensure a function is only called once, none of them seem to fit my specific scenario and objectives. In this case, the function is nested within an object literal, and I aim to either add this utility to Function.prototype or make it more concise in some way. Currently, I am following this approach:

var HugeLiteral={
  subComponent:{
    _name:'subComponent'
    ,_privateFnsEtc:function(){
    }
    ,_init:function(){
      // start of thing I would like to "Macro-ize"
      if (arguments.callee.initialized) {console.error('already initialized');return;}
      arguments.callee.initialized=true;
      // End
      //
      // I wish to do something like
      if (!arguments.callee._proceed()) {return;}// _proceed logs the error
      //
      // or alternatively
      globalRunOnceCheckFn();// uses stack to get this function and do a throw
      // or 
      maybeWrapCallingFunction(this);
      // 
      codeToExecuteOnceHere();
      //
      // or this method which would tend to lock me into a single return point
      this._init=this._init.guardFnOnFunctionPrototype;
    }
  }
  ,_init:function(){
    // Here I could walk through HugeLiteral and perform tasks as needed, 
    // but I am unsure about wrapping the _inits.
  }
};

My primary requirement is that the implementation must work internally within the function. While wrapping the function externally could achieve the goal of running it only once, being able to handle it from inside the function itself is crucial for me.

Answer №1

let object = {
    method: function() {
        this.method = function(){};
        return 'first';
    }
};

console.log(object.method()); // 'first'
console.log(object.method()); // undefined

Answer №2

To ensure a function is only run once, you can utilize an IIFE closure that stores a variable to track its execution status:

var obj = {
    myFunc: (function() {
        var hasRun = false;
        return function(arg1, arg2) {
            if (!hasRun) {
                hasRun = true;
                // include the rest of your code here
            }
        };
    })();
};

Alternatively, create a helper function for cleaner usage and easier reusability of this concept across multiple instances:

// helper function that generates a one-time callable function 
function runOnce(fn) {
    var hasRun = false;
    return function() {
        if (!hasRun) {
            hasRun = true;
            return fn.apply(this, arguments);
        }
    }
}

var obj = {
    myFunc: runOnce(function(arg1, arg2) {
        // place your code here for a function that executes just once
    });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expansive image coverage

My footer design includes a rounded left image, a repeating middle section, and a rounded right image. How can I ensure that it scales perfectly responsively without overlapping? Ideally, the solution would involve adjusting the width of the middle section ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Guide for displaying d3.js chart using a vue.js method and specifying the target div

I'm working on my Vue code and here's a snippet of what I have: new Vue({ el : '#friendlist', data : { friends : [] }, methods : { fetchStats : function(){ const axios_data = { ...

Exploring the concept of template inheritance in Vue.js

Is there a way to implement template inheritance similar to Jade’s extends file.jade? I understand that composition can achieve the same result, but for components like the footer and header which are present on most pages except a few (e.g. login page), ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...

Combine javascript and css sequentially

I have a few tasks that involve combining CSS and JavaScript together. Here is an example of how I accomplish this: gulp.task('javascript', function() { return gulp.src([ libPath + 'jquery-2.1.4.min.js', libPath + '*.js& ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Issue with undefined bindingContext.$data in IE9 on knockout binding handler

I'm attempting to create a unique binding handler that applies role-based access to fields on a page. This custom handler uses the values of other observables from the viewModel to enable or disable input controls based on certain conditions. However ...

Determine the radius using three given points

I am in need of determining the radius at the corners of a rectangle based on some given data points along the curve. The image below provides a visual representation: https://i.stack.imgur.com/7FHq0.png How can I calculate the radius using these specifi ...

What could be causing this JSON object error I'm experiencing?

res.send({ customerDetails:{ fName, lName, }, applicantDetails:{ [ {primaryApplicant:{fName1,lName1}}, {secondaryApplicant:{fName2,lName2}}, {thirdA ...

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...

The Hidden Div containing NicEdit is now shrunk down to a smaller size

Attempting to integrate the NicEdit editor for a hidden textarea stored within a div has presented some challenges. The goal is for the targeted textarea's parent div to be revealed upon the user clicking a button, with the textarea's width set t ...

Securely Connecting to an MQTT Broker with a JavaScript Client (React) while Safeguarding Credentials

Looking to securely connect my React application to a Mosquitto MQTT broker without exposing sensitive credentials to users who can access the JavaScript code. Considering options for authentication, such as using an API with JWT authentication to retriev ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

The magnitude of each new keystroke is squared compared to its predecessor

exploring the relationship between keyboard and console inputs Each subsequent e.key entry is occurring twice as frequently as the previous one. Once it reaches 8-9 characters, the rendering frequency skyrockets to over 1000 times per character. Here&apos ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Steer clear of downloading images while on your smartphone

As I develop a responsive website, I encounter the challenge of optimizing image loading based on viewport size. While using CSS to hide images not needed for certain viewports can reduce display clutter, it does not prevent those images from being downloa ...