javascript context scope

As I delve into the world of JavaScript, please bear with me as I navigate through defining multiple namespaces. Here's an example of how I'm doing it:

var name_Class = function(){
  this.variable_name_1 = {}

  this.method_name_1 = function() {}
}

And then...

var second_name_Class = function(){
  this.variable_name_1 = {}

  this.method_name_1 = function() {}
}

My issue arises when I try to access a variable initialized in the first namespace from the second one. For instance, if I write c = new name_Class(), it seems to reset every array to [], losing the values I assigned. Can anyone provide assistance?

Answer №1

It seems like there may be some confusion in your understanding of the concept.

The following code snippet:

var name_Class = function(){
  this.variable_name_1 = {}

  this.method_name_1 = function() {}
}

is defining a constructor function named name_Class (note that by convention, constructors should have their first character capitalized).

When you execute:

var c = new name_Class();

you are creating a new object using that constructor. The constructor is then bound to the new object 'c' and called, initializing the variable_name_1 and method_name_1 properties of 'c'. Each time you instantiate 'new name_Class()', a fresh object with its constructor bound to it is created. Changes made to other objects instantiated from the function will not impact this newly created variable.

It's important to note that these concepts are unrelated to your second Constructor, which can be utilized independently in the same manner.

In fact, neither of them can be technically considered namespaces - they are more accurately described as classes or types. In programming, a namespace typically refers to a top-level variable on which other variables are defined as properties. By default, variables are declared on the global namespace, often represented by 'window' in browsers.

To create a new object of type name_Class under a namespace 'namespace1', you could do something like this:

var namespace1  = {};
namespace1.c = new name_Class();

Answer №2

If you want to customize values for an object, you have the option to provide arguments when creating an instance. For example:

var CustomObject = function(){
  this.property = arguments[0] || 'default';
  this.callback = arguments[1] || function() {
     alert(this.property);
  }
  this.callback();
}

//Creates an object with default property value
var obj1 = new CustomObject();

//You can also specify your own values
var obj2 = new CustomObject('custom',function(){
  alert('New object created with property '+this.property);
});

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

Tips for integrating AngularJS into Zend Framework 2

Hi there! I am a newcomer to Zend Framework 2 and I am exploring the integration of AngularJS into my project. Currently, I am calling a function in the controller like this: return new ViewModel(array( 'result' => $result, 'use ...

Express.js using GET request to retrieve all data entries from the database

I am facing a challenge in retrieving specific user data using the GET method on Express.js through a Form. Instead of returning only one user's information, it is currently returning all values when the form is used. Here is the code from index.html ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

What does the "done" callback function entail in Node.js?

Many npm packages commonly utilize a "done" callback function in their code. I find it challenging to grasp its purpose. For instance: passport.serializeUser(function(user, done) { done(null, user.id); }); From what I can gather: The "done" function a ...

Resize the div based on the width and height of the window

My goal is to create a system or website that can be fully resizable using CSS and the VW (viewport width) unit. Within this system, I have integrated a GoogleChart that functions with pixels. Now, I am looking for a way to scale the chart using Javascript ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

What is the best way to retrieve a value from an asynchronous function in Node.js?

var fs = require('fs'); var ytdl = require('ytdl-core'); var favicon = require('serve-favicon'); var express = require('express'); var app = express(); app.use(favicon(__dirname + '/public/favicon.png')); ...

What is the best way to ensure that cleanup is always executed at the conclusion of a function

Imagine a scenario where I have the following function (psuedo-code) : function Foo() { let varThatNeedsCleanup = //something if(condition1) { return Error1; } if(condition2) { return Error2; } if(condition3) { return Error3; ...

Obtain offspring from a parent element using jQuery

$(document).ready(function() { $.ajax({ type: "POST", url: 'some/url', data: { 'name':'myname' }, success: function (result) { var result = ["st ...

Galaxy S5 browsers experiencing issues with website responsiveness

I've been using jquery to dynamically remove a div in order to change the appearance of my home screen on smaller devices. It's been successful on my Macbook Air and Iphone X, but unfortunately, it doesn't seem to work properly on Android de ...

403 Forbidden - CSRF Token Not Recognized

I am encountering an issue with Node Express and CSurf - 403 (Forbidden) Invalid csrf token. After reviewing other solutions and attempting all available options, I am still unable to resolve this. The API functions perfectly when tested in Postman. Howe ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Using an if/else statement in a Jade Template to conditionally remove a select option

I'm a beginner with Jade and I've been assigned to add a select option to a webpage. Everything is working well, except for when the drop-down list is empty and the page is refreshed, an empty option element is created. I want to find a way to re ...

Insert PHP File into Division Element

Need help loading a PHP file into a div element without removing existing content? Here's an example: $('.Load_Div').load('example.php'); Let's say the Load_Div already has some content that you want to keep, and you want th ...

The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows: <html> <script> <head> var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name ...

What is the method for obtaining the values from these newly generated text fields?

Every time I click on the "ADD TEXTBOX" button, a new HTML textbox is dynamically created using jQuery's append method. However, I am struggling to figure out how to retrieve and store the values of these textboxes in PHP. $(w).append('<div&g ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...