Is it better to choose "_this" over "self" in JavaScript?

The Airbnb JavaScript Style Guide recommends using "_this" when saving a reference to the object, as seen in their Style Guide.

// bad
function() {
  var self = this;
  return function() {
    console.log(self);
  };
}

// bad
function() {
  var that = this;
  return function() {
    console.log(that);
  };
}

// good
function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
}

However, some books, like AngularJS: Up and Running, argue that using "self" is preferable.

<script type="text/javascript>
    angular.module('notesApp', []).controller('MainCtrl', [function () {
      var self = this;
      self.message = 'Hello ';
      self.changeMessage = function () {
        self.message = 'Goodbye';
      };
    }]);
</script>

So, the question remains - what is the reason for using "_this" over "self"?

Answer №1

Everyone has their own personal preferences when it comes to coding. However, it is generally recommended to stick to using one naming convention consistently within a project's codebase. Mixing and matching different styles like using _this in one function block and that or self in another can lead to confusion and potential errors.

Answer №2

It has been pointed out by different individuals that this is purely a matter of coding style preference. Here's my suggestion: If your team's code base prefers lexical scoping for this, you might want to consider using ES6's fat arrow function as an alternative to avoid creating unnecessary variables.

However, this recommendation all hinges on whether your project is prepared to incorporate ES6 features.

Answer №3

Avoid using self since it is already being used as another reference to the window object. For an example of how you can utilize self as a variable without having to prefix it with window.self, check out this link (located part way down the page): https://developer.mozilla.org/en/docs/Web/API/Window/self

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

Preventing click events with pointer-events property in CSS while still allowing scrolling

Is there a way to use pointer-events: none to disable click events on a specific container while still allowing scroll functionality and an overlay? You can view my fiddle here: https://jsfiddle.net/1eu6d3sq/1/ Currently, when I apply pointer-events: non ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

altering dimensions in three.js

My question may seem a bit silly, but it's about resolution in THREE.js. I have experience with OpenGL and some frameworks related to it, so naturally, I became interested in webGL and Three.js. After trying out some simple demos, I decided to create ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

Is it feasible to indent lines in a template without affecting the content alignment?

Creating a string with newlines that will be included in an email later. if (action) { description = ` Git pull request action: ${action} Git pull request for repo: ${req.body.repository.full_name} Git pull request for repo URL: ${re ...

Spinner Vue Displays while Loading Image from a URL

I am trying to display a loader spinner while an image is loading, but I am having trouble implementing this. Even after debugging and getting true and false values in the console, the spinner is still not showing up. <template> <div class=&q ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Even after setting a new value to a variable in Vue, it may still reference the old

init(){ this.unsortedList = this.selectedVoucher.approvalStepList; // list in original order this.sortedList = this.unsortedList .sort(function(a,b){ if (new Date(a.createDate) < new Date(b.createDate)) return -1; ...

"Getting Started with Respond.js: A Step-by-Step

I've been struggling to find clear instructions on how to properly set up respond.js. Should I just unzip it into the htdocs folder, or do I only need respond.min.js in there? Then, do I simply reference the file like this... <script src="respon ...

The drop-down menu selection is non-functional on mobile and iPad devices when using Bootstrap

<div class="panel panel-default"> <select> <option value="B3">B3</option> <option value="B4">B4</option> <option value="B5">B5</option> & ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

retrieve the php variable value and display it in an input field using javascript

I am looking to combine the variable $variable with the input value using JavaScript $variable= file_get_contents('./env.txt'); <select id="customer_id" name="customer_id" w300 required pj-chosen" data-msg-required=&q ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

Connecting Angular directive with controller

Can someone provide a simple example of a use case? Here is the directive I am working with: angular.module('aahBreakdownLocationMapModule', ['aahBreakdownLocationMapControllerModule']).directive('aahBreakdownLocationMap', [ ...

What is the Extent of Support for JSON?

What level of support does JSON have across different browsers? I recently tested the following: <?php header('Content-type: application/json'); $arr = array('name' => 'Lisa'); echo json_encode($arr); ?> ...

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

I am looking to upload an image to the database using ajax or any alternative method

I need assistance in uploading an image to a Spring Boot backend via AJAX or any other method. Below is the img tag and form I have implemented, along with an AJAX request to send form data. How can I include the image in this process? AJAX request (exclu ...

Display a block by using the focus() method

My objective is : To display a popin when the user clicks on a button To hide the popin when the user clicks elsewhere I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it However, I wanted to ...

Waiting for update completion in Firebase Firestore (Javascript for web development)

When I retrieve a document, update it, and then try to access the updated data, I am getting undefined logged. Can anyone explain why this is happening and suggest a solution for successfully fetching the new data from the document? db.collection("collect ...