Exploring the concept of scoping in two brief JavaScript functions

Can you clarify the distinction between the following pair of JavaScript functions? I understand that variables declared with var are local within the function, and those declared with 'this' keyword are accessible in the outer scope. Are there any other disparities between

function student(param1, param2, param3) {
    this.name = param1;
    this.age = param2;
    this.address = param3;
}

and

function student(param1, param2, param3) {
    var name = param1;
    var age = param2;
    var address = param3;
}

Answer №1

Answer: The first function is used as a constructor to create objects. The second function does not serve any purpose. If you want to implement 'private variables', you can use functional scoped variables in the constructor and access them through instance methods using closures.

To create a student object, you would use the first function by passing parameters that will be assigned to the newly created student.

function student(param1, param2, param3){
this.name = param1;
this.age = param2;
this.address = param3;
}

var student1 = new student('steve', 22,'333 E 3rd Ave');
var student2 = new student('rachel', 34,'111 N 1st St');

console.log(student1.name); // 'steve'
console.log(student2.name); // 'rachel'

The second function does not fulfill the role of a constructor. It declares variables with functional scope which are not utilized, and they will be garbage collected once the function execution ends.

If you attempt to use the second function like a constructor, it will not work:

function student(param1, param2, param3){
var name = param1;
var age = param2;
var address = param3;
}

var badStudent = new student('Greg', 22,'222 W 2nd Rd');

console.log(badStudent.name); // undefined

Edit

A method to achieve 'private member variables' using variables declared with var inside a constructor is to use closures:

function student(param1, param2, param3) {
var name = param1;
var age = param2;
var address = param3;

this.getName = function(newName) {

if (newName)
name = newName;

return name;
};
}

var myStudent = new student('steve', 22,'333 E 3rd Ave');

console.log(myStudent.name);

console.log(myStudent.getName());

console.log(myStudent.getName('dan'));

console.log(myStudent.getName());

By using closures, the instance method getName retains references to the variables declared in the constructor even after its execution. This allows you to access and modify these 'private' variables through the instance method.

Answer №2

The main distinction between variables declared with this and var lies in their scope. Variables assigned to this will become part of objects, while those declared with var may be considered private. This is not always guaranteed, as it depends on the use of return. If return is not utilized, then they will indeed be private.

Example

function Person(firstName, lastName, dob) {
  var _firstName = firstName, 
      _lastName = lastName,
      _dob = new Date(dob);
  
  this.fullName = _firstName + " " + _lastName;
  this.age = (new Date()).getFullYear() - _dob.getFullYear();
}

var person = new Person('John', 'Doe', '1980/05/25');
console.log(person);
console.log(person._firstName)

In the above code snippet, the variable _firstName was created using var, making its scope limited to the function only. Consequently, attempting to access it outside the function will result in an error.

To summarize, this can be used to define public properties, while var can be used for private ones.

Answer №3

When it comes to creating objects in JavaScript, we typically use the 'function' keyword as a constructor. These constructor functions are responsible for returning an object. If you declare a variable using 'var' instead of 'this.varName', it means you are attempting to use those variables to create an object. Variables declared with 'var' are simply local variables within the function scope.

On the other hand, when you use 'this.variableName', you are actually creating a property for the object that the constructor function is trying to instantiate.

'this.' refers to the object being created by the constructor function. 'var variableName' declares a local variable that is not a property of the 'this' object.

function student(param1, param2, param3) {
    this.name = param1;
    this.age = param2;
    this.address = param3;
}

var t = new student('farhad', 28, 'address');

This will create the following object:

t{
   name: 'farhad',
   age: 28,
   address: 'address'
}

However, if we look at the following example:

function student2(param1, param2, param3) {
    var name = param1;
    var age = param2;
    var address = param3;
}
var t2 = new student2('farhad', 28, 'address');

We'll see that the object 't2' does not contain any properties.

Answer №4

this is a crucial keyword utilized within functions that holds the value of the object triggering the function.

When used, this specifically points to the particular instance of the object calling the function and doesn't receive a value until the respective object initiates the function in which it's declared.

function Employee(name, age, address) {
      this.firstName = name;
      this.employeeAge = age;
      this.homeAddress = address;
      this.introduce = function() {
        console.log(this.name + this.age + this.address)
      }
    }
    var employee1 = new Employee('John', 30, '123 Main St');
    employee1.introduce(); // John30Main St

In contrast, with

var firstName=name; var employeeAge=age; var homeAddress=address;
, each parameter is being assigned to a variable, with these variables limited in scope solely inside the function itself.

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

When testing units, the scope method in an AngularJS directive fails to execute

I am facing an issue with my Mocha test: 'use strict'; /////////////////////////////////// describe('all admin page directives', function () { let scope, $compile, element, tmp; beforeEach(module('app')); beforeEach( ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

How to insert text into a text input using onKeyPress in react.js

I am looking to simulate a typing effect where the phrase 'Surveillance Capitalism' is inputted letter by letter into a text input field as a user types. However, I encounter an issue when trying to add each individual letter into the input; I re ...

Instructions for converting SCSS to CSS and storing the CSS code as a string in a variable

I am currently developing a Single Page Application (SPA) using Vue (specifically Quasar), and I have the following requirements: Load the contents of a CSS file into a JavaScript variable or Vue data property dynamically The CSS file should be generated ...

What is the best way to transfer data from one function to another file in React without directly calling the component or using props?

filename - Header.jsx import { useEffect, useState } from 'react' import { getValue } from './Input' import TextField from '@mui/material/TextField'; export const Header = () => { const [search, setSearch] = useState( ...

Issue with sending multiple files using FormData and axios in Vuex with Laravel. Server side consistently receiving null. Need help troubleshooting the problem

After trying the solution from my previous question Vuex + Laravel. Why axios sends any values but only not that one, which come's with method's parameter?, I realized that it only works when passing a single argument in axios. I managed to succe ...

AADSTS9002326: Token redemption from different origins is only allowed for the 'Single Page Application'

Attempting to make a cross-origin request to obtain an access token on my React single-page application running on localhost. Initially encountered the 'Access-Control-Allow-Origin' error, which was resolved by setting up a proxy in webpack. How ...

Animating the fixed location with CSS and JQuery

I'm attempting to create a seamless transition from one form field type to another. However, when I add another <input> element, the following elements do not animate into their static positions. $("#switchlogin").click(function() { //Creat ...

Ways to showcase logs on the user interface

After configuring a set of operations in the UI and initiating the operation, a Python script is called in the backend. It is necessary to display the logs generated by the Python script on the UI. I managed to implement this in a similar way as described ...

Converting Embedded Elements into Arrays

A pre-existing project was handed to me with the following data structure: [ { "key": "username", "value": "" }, { "key": "password", "value": ...

The function to refresh content is causing errors in the code

Creating a comment and replies form where the replies display underneath each comment. I've encountered an issue where I can post replies normally, but when attempting to delete a reply, I must refresh the page. After refreshing, I'm only able to ...

What is the best way to replicate text in ReactJS?

I need some help with implementing a copy to clipboard feature in ReactJS. My goal is to have text copied to the clipboard when a user clicks on a link. My current setup involves using Chrome 52 and I am only focusing on supporting this browser at the mom ...

Set the title attribute according to the content of the <p> tag

Recently, I encountered a situation where I had numerous p tags with a specific class (let's call it .text). My task was to include the title attribute containing the text of each tag. For example: <p> Hello, world </p> This would resul ...

How can you place text on top of an image using JQuery and CSS?

I've been working on overlaying text over an image using Jquery and css. The overlay text is displaying nicely on the image, but I'm struggling to change the font and size of the text. I attempted to make changes in the CSS for the font family an ...

Tips for extracting text from a textarea while retaining newline characters:

When using jquery, my goal is to retrieve the text from a textarea element with new lines represented as \n instead of br tags. However, I encountered an issue where Firefox debugger does not display the \n or br characters when I select it and r ...

Acquiring information from a variable via an HTTP request

I am new to making http requests and using PHP. I have a code snippet that makes an AJAX call: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc( ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

``Despite running $scope.$digest, the scope variable is failing to update in the view

.controller('PizzaCtrl', ['$scope','$state','$ionicLoading', function($scope, $state, $ionicLoading) { $scope.$emit('menu-refresh-request'); $scope.$on('menu-refresh-response', funct ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Challenges with AngularJS validation

I'm facing a couple of issues related to validation in AngularJS Problem 1: How can I achieve the following in the controller using AngularJS and not in the view? vanilla js code document.getElementById('InputId').value.length I attempt ...