Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods.

//CODE

class Form{ 
    constructor(){
        var self = this;
    }   

    assemble(){
        log(self);
    }
}

//INVOCATION

var form = new Form();
form.assemble();

//RESULT

window object (not a reference to the class object)

Answer №1

this is not a variable. It functions more like a concealed argument in functions.

In the given example, you cannot access self because it is a local variable confined within the constructor and therefore unavailable to your assemble method.

For this particular scenario, you actually do not require self at all; simply utilize this:

class Form {
    assemble(){
        log(this);             // ***
    }
}
var form = new Form();
form.assemble();

If you were passing form.assemble into something where the correct usage of this was not guaranteed, you could define assemble as an instance function member by defining it within the constructor; thus closing over self. Nonetheless, in ES2015 and beyond, there is no need for self; instead, use an arrow function which closes over this:

class Form {
    constructor(){
        var self = this;
        this.assemble = () => {
            log(this);
        };
    }   
}
var form = new Form();
form.assemble();          // Functions correctly
var f = form.assemble;
f();                      // Also works fine

However, chances are high that this additional step is unnecessary.

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

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Tips for extracting and dividing the value of an input field using jQuery

My system includes an input search field where I can enter the make and/or model of a vehicle to conduct a search based on that term. The challenge arises when attempting to distinguish between the make and model, especially for makes with multiple words ...

Extracting a variable established on the client side and passing it to a server-side node backend

I am currently working on creating a comments section for a web application. The front end of the app displays information about the threading level of each comment. When users submit comments, I need to pass this threading information to the back end in o ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...

Establish a predetermined selection for a drop-down menu

How can I set a default value for a dynamically filled dropdown menu featuring all 12 months in KnockoutJS? I want the default value to be the current month. This is how I am populating the dropdown with information: self.setMonthData = (data ...

Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator: ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'" To access these elements, we can compile all the ones with fa-minus and store them in a lis ...

Leveraging deferred for linking loops involving several ajax requests

Despite the fact that several questions have been answered on this topic, none of them seem to be effective in this particular scenario. function login(u,p) { console.log(1); return $.post(url, {u,p}); } function out() { console.log(3); //a f ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Adjusting the height of a Jquery Fancybox to allow for scrolling down

I've implemented fancybox to display certain pages on my website, but I'm struggling with setting a fixed height and enabling scrolling for content that exceeds this height within the fancybox. Here are the parameters I have used: <script> ...

To effectively utilize the expect function in testing, should you use it over softAssertAll or find a way to explicitly display in the test results that the softAssertAll has successfully passed? (Error

Utilizing the 'soft-assert' library (soft-assert library) allows me to implement assertions in my test steps without halting the entire test if any of them fail. While softAssertAll() command works effectively to verify all soft-assert at the en ...

Adjusting the inner div dimensions to be 100% of the body's size without relying on the parent div using JavaScript

I have a main layer with multiple layers stacked on top of it. I need the second layer to extend its width to match the body's width. Main Project: http://example.com What I've tried: I looked into: Solution for matching div width with body ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

CF component not able to accept arguments when invoked by JavaScript through cfajaxproxy

Ever since updating to ColdFusion 2016 Update 4, I've been experiencing a new issue. Here's the code snippet: <input type='button' name='btn' value='Click me' onclick='proxyFunc();'> Incorporating ...

What is causing the table to not be displayed in this Javascript program when it is used in a

I am currently experimenting with incorporating an infinite loop before the prodNum and quantity prompts to consistently accept user input and display the output in a table. Although the program is functional when executed, it fails to showcase the table ...

Step-by-step guide on repairing a countdown clock using JavaScript, HTML, and

I'm having issues with my JS on my website. I am new to this and currently in the process of setting up a website. I want to add a timer to show when the site will be active. It seems like there is an error somewhere in the JS code that I can't ...

how to use jquery to indicate that a checkbox is selected

click here to see the image $(document).ready(function() { $('.editbtn').on('click', function(){ $('#editmodal').modal('show'); $tr=$(this).closest('tr'); var da ...