What is the reason behind plugins frequently neglecting to properly privatize their functions?

Many plugins utilize an underscore to indicate a function is private while still allowing public access. But why? We have options like .call, .apply, or .bind for managing the "this" keyword, or we can use the "self" pattern which is reportedly 60% faster according to this discussion: Will Function.prototype.bind() always be slow?

Is it considered lazy programming or is there something I'm overlooking?

Example of exposing a private function:

var simplifiedPlugin = function() {
    this.name = 'simples';
    this._privateFunc = function() {
        console.log('Why am I here?');
    }
    this.publicFunc = function() {
         // stuff, then
         this._privateFunc();
    }
}
var pluginInstance = new simplifiedPlugin();

Utilizing the self pattern:

var selfSimplifiedPlugin = function() {
    var self = this;

    this.name = 'self is also simples';

    function _privateFunc() {
        console.log('Nobody knows am I here');
        //I can use self instead of this
    }

    this.publicFunc = function() {
         // stuff, then
         _privateFunc();
    }
}

var anotherInstance = new selfSimplifiedPlugin();

With the self pattern, the private function can still access the this context by using self.fn() instead of this.fn()

Answer №1

One of the main reasons for choosing this approach is the ease of debugging.

In my experience, current JavaScript debuggers struggle to inspect closed-over symbols effectively, especially when the compiler has optimized the closure well.

By following the underscore convention, you can still access these 'private' functions reliably in challenging situations, while the underscores clearly indicate that they are intended for internal use only.

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

Avoid triggering the onClick event on multiple submit buttons when the form data is deemed invalid by vee-validate

How can I ensure that the onClick event on a button is only called if certain input fields are valid, using vee-validate ValidationObserver? The validation should apply to individual buttons within a form, rather than the entire form itself, as there are m ...

How can I ensure that the height of my dropdown menu covers the entire screen without being limited by the page height

I'm trying to adjust a dropdown menu so that it fits perfectly within the screen size, covering the entire height without showing any content beneath or below it. Currently, the menu covers the screen on some pages but scrolls and appears too large du ...

Obtain the popup URL following a fresh request using JavaScript with Playwright

I'm having trouble with a button on my page that opens a popup in a new tab. I have set up a listener to capture the URL of the popup when it opens: page.on('popup', async popup => { console.log('popup => ' + await pop ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

How can I retrieve an empty object from the database using Angular 5?

Hey there! I'm facing a little issue that I need help solving. I asked a question before when things weren't clear, but now they are (you can find the previous question here). I'll share my code and explain what I want to achieve shortly. H ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

JXBrowser comparable

In a Java project of mine, I have been utilizing JXBrowser to showcase Google Maps for route tracing purposes. However, the license for JXBrowser has recently expired after just one month. Unfortunately, simply requesting another license is not an option ...

Encountering an Unknown Error while Parsing JSON in Google Apps Script

Having trouble parsing JSON data retrieved from an API call. The error message "TypeError: Cannot read property "id" from undefined. (line 42, file "")" keeps popping up. I'm fairly new to Apps Script. Any thoughts on what might be causing this issue? ...

How can the order of elements appended to a documentFragment be controlled when they are returned asynchronously?

Curious question here... I am constructing my in-memory DOM and relying heavily on promises. Let's say I have this snippet inside a loop: target = document.createDocumentFragment(); promises = [], pass, skip, store; for (i = 0; i < foo; i += 1) ...

Delays in running multiple jQuery UI effects at the same time

When I implement a show and hide effect with slide on different divs simultaneously on my page, I encounter some lag in the animation. However, I noticed that if I run the show effect only after the hide effect is completed, the lag disappears. I am curiou ...

The Angular 2 bootstrap function is throwing an error stating that the argument type AppComponent cannot be assigned to the parameter type Type

Presenting my very first Angular 2 application with a simple Hello World example, inspired by the Angular 2 quick start guide. import {Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; @Component({ ...

Error encountered when calling the function .jstree() on a tree structure

While working on MVC4, I attempted to implement a jstree but encountered an issue where the tree view was not displayed when running my application. Upon investigating with Firebug, I came across the following error message: "TypeError: $(...).jstree is ...

ERROR_UNSUPPORTED_ESM_URL_SCHEME - issue with next-sitemap plugin

I have a project utilizing next-sitemap with Node.js version v14.11.0. next-sitemap.config.js module.exports = { siteUrl: 'https://*****.com', generateRobotsTxt: true, robotsTxtOptions: { additionalSitemaps: [ 'htt ...

Decoding Lodash: Unveiling the findwhere and copy operator in the realm of

Could someone please explain why using Lodash to fetch an object with findWhere allows for a reference copy that enables dynamic changes based on user actions, while the same operation using the copy operator fails to update the source object? I have creat ...

JQuery mishandles its left positioning

Here's the code snippet I've been working with: $(this).closest("p").after('<strong>' + arMess[iCurIndex] + '</strong>').next().animate({ top: $(this).offset().top - 57, left: -$(this).widt ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

JQuery / Javascript - Mouse Position Erroneously Detected

I'm currently working on developing a drawing application where users can freely draw by moving their mouse over a canvas. My goal is to create a pixel at the precise location where the user drags their mouse. However, I've encountered an issue ...

ReactJS integration issue with Material Design Lite (import/require problem)

I am currently integrating Google's Material Design Lite with ReactJS. Specifically, I am utilizing the Spinner Loading and Text Field components from the MDL library. However, I am encountering an issue when switching routes using React Router. The ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...