In the realm of JavaScript, "this" is a key player when referring to an object within a factory

I created some JavaScript classes and FunctionFactories for them, but I believe there are errors in my implementation.

To make the code more understandable, I decided to rename certain parts of it.

The main class is called the "root"-class, which has children that are added later on.

function templateRoot(){
    this.id = "root";
    this.parent = null;
    this.children = [];

    this.editable = true; // bla

    this.render = function(){
        $.each(this.children,function(i,obj){
            this.children[i].render();
            var baseButtons = this.getBaseButtons();
            $('#'+this.id).append(baseButtons);
        });
    };
    this.addBase = addBaseFactory(this);
};

The "addBase" attribute receives a function from the addBaseFactory...

function addBaseFactory(that){
    return function(){
        var newBase = new base(that.children.length, that.id);
        that.children.push(newBase);
    };
}

...and here is the base class used to generate an object in the "addBase" method:

function base(count, parent){
    this.id = parent+"_base"+count;
    this.parent = parent;
    this.children = [];
    this.remove = function (){
        $('#'+this.id).remove();        
    };
    this.render = baseRenderFactory(this);
    this.addChild = addChildFactory(this);
    this.getBaseButtons = function(){
        var addAttributeButton = new $("<button>+ Attribute</button>").button();
        var addTextButton = new $("<button>+ Text</button>").button();
        return [addAttributeButton, addTextButton];
    };
}

The issue arises when debugging the code and setting a breakpoint within the "render" function of the root-object. At this point, "this" refers to the "base" object instead of the "root" object. This confuses me because the "root" object should be the owner of this function, and the base has its own render function which is not directly called there.

Even in the line:

$.each(this.children,function(i,obj){

"this" points to the "base" object while it should be referring to the "root" object.

I hope someone can assist me with this :-)


EDIT:

The code to execute it:

var test = new templateRoot();
test.addBase();
test.render();

EDIT 2:

In the "addBaseFactory," "that" correctly references the "base" object.

Answer №1

Your explanation seems a bit confusing, so I may have misunderstood your intentions. It appears that you are expecting the this keyword within your nested functions to refer to the same object as in the outer templateRoot() function. However, it's important to note that in JavaScript, each function has its own unique this object and nested functions do not inherit from the containing function.

An alternative solution is to utilize the concept that nested functions can access variables from their parent functions. Here is an example implementation:

function templateRoot(){
    var self = this; // save a reference to this for use in nested functions
    this.id = "root";
    this.parent = null;
    this.children = [];

    this.editable = true;

    this.render = function(){
        $.each(self.children,function(i,obj){
            self.children[i].render();
            var baseButtons = this.getBaseButtons();
            $('#'+self.id).append(baseButtons);
        });
    };
    this.addBase = addBaseFactory(this);
};

To gain a deeper understanding of how the this keyword works in JavaScript, you can visit MDN.

Answer №2

Is it possible that this will display the children of its children, as jQuery sends each child individually?

this.display = function(){
    $.each(this.children,function(i,obj){
        this.children[i].display();
        var baseButtons = this.getBaseButtons();
        $('#'+this.id).append(baseButtons);
    });
};

By the way, in which context is addBaseFactory invoked? I am concerned that the "this" in the base might point to that particular scope.

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

What is the method for retrieving a temporary collection in a callback function when using node-mongodb-native find()?

Is it possible to retrieve a temporary collection from a find() operation instead of just a cursor in node-mongodb-native? I need to perform a mapReduce function on the results of the find() query, like this: client.open(function(err) { client.collect ...

Loop through the elements of a class in JavaScript and choose all except for the one that was

Imagine having 5 div elements, each with a similar onclick-function that hides the other divs when clicked. HTML: <div id="1" class="divs" onclick="hide()"></div> <div id="2" class="divs" onclick="hide()"></div> <div id="3" cla ...

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

Updating the iFrame source using jQuery depending on the selection from a dropdown menu

I want to create a dynamic photosphere display within a div, where the source is determined by a selection from a drop-down menu. The select menu will provide options for different rooms that the user can view, and the div will contain an iframe to showca ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

What steps should I follow to effectively store this JSONB data in PostgreSQL by utilizing node-postgres (pg)?

After receiving information in the GET URL, I need to pass it into JSON format and save it with increasing IDs into a PostgreSQL database. However, the code I wrote does not seem to be saving anything without any errors: // Initializing Pg const { Client ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

Changing a particular field value within an array of objects in Angular 4

I have a scenario where I created a class called security: class security { public id:number; public name:string; } Next, I initialized an array of security objects: let s:security[]=[{id:1,name:'Alex'},{id:2,name:'John'},{id:3,nam ...