Exploring the inner workings of self-referencing mechanics in functions

In a recent coding scenario, I encountered this situation: I attempted to define the func1() function and add several static methods to it simultaneously by passing it through the _init() function along with a hash containing properties to attach. However, I later discovered that the function did not remain declared within the current scope after the _init() function executed its task. It was only temporarily defined and then garbage-collected after the _init() run (to the best of my knowledge). Here is an excerpt of the code:

// 
// #_init
// merge src{} into target{}, overwriting
// 
var _init = (function (target, src) {

  var _ = this;

  if (_.isobj(target))
    _.keys(src).forEach(_.pass, {
      src    : src,
      target : target
    });

  return target;

}).bind({

  isobj : (function (node) {
    return node === this(node);
  }).bind(Object),

  keys  : (function (node) {
    return this.keys(this(node));
  }).bind(Object), 

  pass  : function (field) {
    this.target[field] = this.src[field];
  }

});

I was hoping to 'batch-init' it here by adding static methods at the same time:

_init(function func1(e) {
  var _api = func1.pop(arguments);
  var node = this;
  // and stuff...
}, {
  pop: Function.prototype.call.bind(Array.prototype.pop),
  // ...etc
});

Subsequently, when I attempted to reference it later on, I encountered an error:

x = func1();
// ReferenceError: func1 is not defined
// x = func1()

Assigning the output of _init() to var func2 resolved the issue as I could now reference and utilize the function. What confuses me is that when using console.log() to display func2, it shows 'func1()'. Yet, trying to directly reference func1 results in a ReferenceError:

// 
// #func2
// 
var func2 = _init(function func1() {
  return func1.pop(arguments);
}, {
  pop: Function.prototype.call.bind(Array.prototype.pop)
});

console.log(typeof func2, func2, func2(1,2,3));
// function func1() 3

console.log(func1(1,2,3));
// ReferenceError: func1 is not defined
// console.log(func1(1,2,3));
//

Can anyone clarify why the reference to func1 was not successfully created, yet it seemed available to func2 (which was able to use it)?

Answer №1

I am confused as to why the func1 reference was not created initially, but somehow became available to func2 later on. How is this possible?

This phenomenon is a result of how named function expressions work. The name (func1) is only accessible within the function body itself and not outside of it. The process of passing the created function to _init and then assigning it to func2 is a separate and unrelated aspect.


I attempted to declare the func1() function and include some static methods with it

It is advisable to avoid doing this unless those static methods are intended to be public and not just basic helper functions. Instead, utilize the revealing XY pattern (IEFE) to keep your utility functions within the closure scope:

var _init = (function() {
  function isobj(node) {
    return node === Object(node);
  }
  function pass(field) {
    this.target[field] = this.src[field];
  }
  var keys = Object.keys;

  return function (target, src) {
    if (isobj(target))
      keys(src).forEach(_.pass, {
        src    : src, 
        target : target
      });
    return target;
  };
});
var func2 = (function() {
  var pop = Function.prototype.call.bind(Array.prototype.pop);

  return function func1 () {
    return pop(arguments);
  };
});

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

Verify a roster within a display by utilizing annotations

My solution involves using a listbox to display a list as shown below, and I am also utilizing Chosen.js to allow for selecting multiple records. @Html.ListBox("AllLanguages", new SelectList(ViewBag.Languages, "Id", "Language1")) <div id="languagesDi ...

Tips for displaying the number of selected values in a select box label (e.g. Choose an Option)

I am currently using the jQuery multiselect API in my application to allow users to select multiple values. However, I am facing an issue where I need to fetch all the selected values when a button next to the multiselect box is clicked. Unfortunately, I h ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

Postponed attaching event listeners to a Vue 3 instance within an iframe

Due to a specific requirement, I find myself in need of running a Vue instance inside an iframe. After some research and adjustments based on this thread from the Vue forum, I was able to achieve this goal while adapting the code for Vue 3 and removing unn ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...

unique array that shuffles every time it is reloaded, utilizing only javascript

I have created a string array that holds 6 different classes. Whenever I click a button, a new class is generated randomly. However, the issue arises when I click the button again and get the same class instead of a new random one. Even after reloading the ...

Checking for the Existence of a Class Element within a String using JavaScript

Within my web project, there is a scenario where if a user has been logged out in one browser tab, they will automatically be redirected to the login page in any other browser tab after interacting with that page (such as clicking on a link). However, this ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

A customizable JavaScript NPM Package designed to specifically escape XML special characters while preserving the integrity of the XML tags

Seeking recommendations for a JavaScript npm package that can escape the values in an XML document while preserving the XML tags. Ideally, looking for a solution that only allows letters A-Z (upper and lower case), digits 0-9, and spaces within the value ...

Place an element in relation to the vertical size of a div that includes written content

Currently, I am working on implementing a button with a popup that appears underneath it when the user hovers over it. The specific requirements for this setup are: The size of the button should not affect the size of the popup The popup should always be ...

Enhance the functionality of the kendo grid by incorporating additional buttons or links that appear when the

Is there a method to incorporate links or buttons when hovering over a row in a kendo grid? I've searched through the documentation and looked online, but haven't found a solution. I'm considering if I should modify my row template to displa ...

Is the HTML Page loading before the AJAX call is made?

On my HTML Page, I have a button tag that looks like this: <button ng-hide="alreadyFreinds()" type="button" class="btn btn-primary btn-lg">Friend</button> However, when attempting to access certain parts of the alreadyFriends function shown b ...

Getting the parent object based on a filtered nested property can be achieved by utilizing a

I am currently facing an issue with filtering an array of nested objects. The problem arises when trying to filter the parent object based on a specific property within its child object. let line = "xyz"; let data = [ { "header": { ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

Ways to retrieve slider value when button is clicked?

I am currently working on a range-slider that has two ranges and I need to retrieve the slider value in my javascript code. Here is my approach so far: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.cs ...