I'm struggling to understand why the `Logger` class isn't available during my exploration of a JavaScript Mixin pattern guide

Currently, I am delving into the world of programming and stumbled upon this tutorial. While following along, I encountered an issue in the console displaying the error message

ReferenceError: Logger is not defined --> }(Logger))
. It seems that the discrepancy between the tutorial's code and mine lies in the use of underscore's extend versus the extend method (function) that I opted for from another source.

    function extend(destination, source){
        for(var k in source){
            if(source.hasOwnProperty(k)){
                destination[k] = source[k];
            }
        }
        return destination;
    }
    (function () {
        var Logger = {
            log: function (message) {
                if (window.console && typeof console.log === "function") {
                    console.log(message);
                }
            }
        };

        return Logger;
    }());

    (function ( Logger) {
        var MyObject = function () {
            this.doSomething = function () {
                this.log("My Object is doing something!");
            };
        };

        // This copies the members of the `Logger` object onto the prototype of `MyObject`
        extend(MyObject.prototype, Logger);

        return MyObject;
    }(Logger))

    var obj = new MyObject();
    obj.doSomething();

Perhaps my struggle lies in grasping the usage of self-invoking anonymous functions.

Answer №1

Logger is not defined because it is declared as a local variable inside the first self-invoking function. To make it accessible, you can define it like this:

var Logger = (function () {
        var Logger = {
            log: function (message) {
                if (window.console && typeof console.log === "function") {
                    console.log(message);
                }
            }
        };

        return Logger;
    }());

Similarly, you have the same issue with MyObject, so you need to modify it like this:

var MyObject = ( function() { .... } (Logger) )

Answer №2

Since you are not saving the result produced by the unnamed function that initializes the Logger object.

var Logger = (function () {
    var Logger = {
        log: function (message) {
            if (window.console && typeof console.log === "function") {
                console.log(message);
            }
        }
    };

    return Logger;
}());

Therefore, you now have access to the Logger object.

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

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

Developing a custom JavaScript function to iterate through a group of html elements

In my mission to create a function that loops through a set of HTML elements and gathers their values, I aim to then utilize those values to produce an HTML textarea. Thus far, I've established a series of HTML input boxes and a JavaScript function f ...

Implementing dynamic https URL embedding in AngularJS based on the user's browser location

When my webpage built with angularjs is launched using https, all urls within the page should also use https instead of the default http. Is it possible to make angularjs use either http or https based on the initial request? Here are some example embedd ...

How can I determine the package version that is being used when requiring it in Node.js?

I am currently working on resolving an issue with a node module that does not have a package.json. The module contains references to cheerio and superagent: var log = console.log.bind(console), superagent = require('superagent'), cheerio ...

Mandate that users select from the available place autocomplete suggestions exclusively

I have integrated the "Places" Google API to enable address autocomplete in an input field on my website. However, since the service is limited to a specific area, I have implemented an autocomplete filter. The issue I'm facing is that users are stil ...

Guide to retrieving IDs of images on a canvas during drag and drop functionality

I've developed a finite state machine drawing tool that includes drag-and-drop functionality for different images, such as states and arrows. Each arrow creates a div tag for the transition, with unique ids assigned to every state, arrow, and transiti ...

Does the Array Splice method always remove an item from the end?

I'm having trouble with deleting an item from an array using Array.splice. It seems to always delete the item from the end instead of where I want it to be removed. I'm working with Vue.js and dynamically adding items to an array, but when I try ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Is React the best solution for managing a lengthy list that requires constant data updates?

In order to display a long list with over 2000 entries that changes dynamically, I am utilizing react redux. Each second, at least one new row is added to the list data. My current approach involves mapping through the list data in the render method like t ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this: <script type="text/javascript> var rootpath = ""; $(document).ready(function () { rootpath = "@VirtualPathUtility.ToAbsolute("~/ ...

Looking to dynamically display users added to an array in a table using Angular and JavaScript?

As a newcomer to javascript and angularjs, I recently attempted to build a table that would display all users in an array dynamically as new users are added through a form. However, each time I run my code, I encounter the error message "Fill out the entir ...

Include a return or delete from the default IO statement

I am utilizing an intersection observer that alters the header's font-color and background-color based on the content intersecting with it. This change is determined by the presence of data-color and data-background attributes declared on the div/sect ...

Manipulating and filtering an array of objects in JavaScript/jQuery

Looking to simplify my array manipulation in Javascript, I need to subset based on key-value matches. I have an array called js_obj, and my goal is to modify objects where a certain condition is met. Consider the structure of my array: js_obj = [{ wo ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

How can JavaScript allow access to files outside of a web server environment? Could .htaccess provide a

Currently, I'm facing a challenge with my local server on Mac 10.8. I am trying to serve files such as videos and images from an external hard drive. The path for the external hard drive is HD: /Volumes/ while the web server's path is /Library/Se ...

What is the process for exporting data from MongoDB?

Recently, I created a web application for fun using Handlebars, Express, and Mongoose/MongoDB. This app allows users to sign up, post advertisements for others to view and respond to. All the ads are displayed on the index page, making it a shared experie ...

What is the proper way to incorporate an if statement within a return statement in React components?

I have encountered an issue while trying to map objects in my array. Everything works perfectly when mapping all the objects, but it becomes problematic when I attempt to map just one object from the array. Here is the code for my array: const slides = [ ...

403 Error Code - Access Denied when trying to access Cowin Setu APIs

While attempting to create a covid vaccine alert using the Cowin Setu API (India) in nodejs, I encountered a strange issue. Every time I send a get request, I receive a 403 response code from cloudfront stating 'Request Blocked', although it work ...

Encountering issues with AngularJS number filter when integrating it with UI grid

When using the angularjs number filter in angular-ui-grid, I am facing an issue. The filter works perfectly fine within the grid, but when I export the grid to csv and open it in Excel, the formatting is not maintained. I have included the filter in the e ...