Uncertainty surrounding the concept of JavaScript objects

What is the reason for this not functioning properly?

function displayValue(a,b){
     this.a = a;
    this.b = b;
    $('p').text(a + " " + b);
}

var display = new displayValue();
display('1','2');

How does this still work without needing the 'new' keyword?

function displayValue(a,b){
     this.a = a;
    this.b = b;
    $('p').text(a + " " + b);
}

var display =  displayValue('1','one');

If I use the new keyword, does it mean that an object is being created? What methods can be used to modify the properties of displayValue?

Answer №1

how come this function works even without using the 'new' keyword?

The initial example provided does not function properly. Instead of getting the expected output, which should be "undefined undefined" within the paragraph elements, an error will occur in the console when trying to call the display function since it is not defined as a function.

Does using the new keyword create an object?

Indeed. The utilization of the `new` operator generates a fresh object and then proceeds to invoke the constructor function where `this`, within the function, refers to the newly created object.

In the second scenario where the `new` keyword isn't employed, during the invocation of displayValue, `this` actually points towards the window object which serves as the global object in browsers. (In cases utilizing JavaScript's strict mode, `this` would resolve to `undefined` leading to an error while attempting `this.a = a;`).

How can one modify the property of displayValue?

Regrettably, the question posed is somewhat unclear. To elaborate on creating a constructor function that yields an object encompassing properties `a` and `b`, used for updating the text of a paragraph based on these properties, the following approach could be adopted:

// Declaration
function DisplayValue(a, b) {
    this.a = a;
    this.b = b;
}
DisplayValue.prototype.display = function() {
    $("p").text(this.a + " " + this.b);
};

// Usage
var d = new DisplayValue(1, 2);
d.display(); // Modifies all paragraphs to "1 2"
d.a = "A";
d.b = "B";
d.display(); // Alters all paragraphs to "A B"

Answer №2

JavaScript functions have two distinct roles:

1- They can function as a method, similar to how you've used it in your second block. 2- They can also act as a Class to create objects, as demonstrated in your first block.

The same function can serve different purposes. For example:

var display = new displayValue();

This code indicates that you want to instantiate an object based on your Class (the function). By using the new keyword, display becomes a JavaScript object and its properties can be accessed like this: display.a or display.b. However, when used simply as a method like this:

displayValue('1','one');

In this case, the function is just being called. The important point here is that this within this function will refer to the function's containing object, which is typically the top-level class or the window object. In your function: function displayValue(a,b){ this.a = a; this.b = b; $('p').text(a + " " + b); } When you use this.a = a;, it generally signifies that you intend to utilize it as a Class or as a method within the top-level class, like so:

function Display(){
    this.displayValue=function displayValue(a,b){
       this.a = a;
       this.b = b;
       $('p').text(a + " " + b);
    }
}

or

function Display(){
   //constructor
}
Display.prototype.displayValue = function displayValue(a,b){
   this.a = a;
   this.b = b;
   $('p').text(a + " " + b);
};

In this scenario, if you attempt var obj = new Display();, the this keyword within the displayValue function will point to the current instance of Display, which is obj.

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

Ways to selectively implement the callback of setState using hooks in specific locations, rather than applying it universally

There are times when I need to set a state and perform an action afterwards, but other times not! How can I achieve this using hooks? Sometimes, I want to call a function or do something after setting the state: this.setState({inputValue:'someValue& ...

Can you explain the distinction between using single and double quotes in my JavaScript and CSS code?

Is there a significant distinction between using single or double quotes in JS and CSS? Does it depend on personal preference, or are there certain instances where one is preferred over the other? In W3Schools, they employ single quotes for url('&apo ...

The jst.js error in sails JS template indicates that the variable _ cannot be found

I am brand new to the world of programming and am currently diving into JavaScript and Sails JS. I must admit, I am enjoying the learning process so far, but recently encountered a problem that has left me scratching my head. Please bear with me as I may n ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

leveraging jQuery mobile for asynchronous requests

I've been attempting to print a jQuery mobile element using ajax, but I'm running into an issue where the result isn't being encoded as jQuery mobile is intended to do. Below is a simplified excerpt of the JavaScript code responsible for t ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

Troubleshooting problem with list rendering in a Nativescript-vue GridLayout

As a newcomer to nativescript, I am utilizing GridLayout in an attempt to optimize layout nesting for better performance. In my template, I have an image followed by a vertical list of four items next to it. However, only the first item on the list is visi ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

Is it possible to activate the onChange event when the input value is being modified by the state with information obtained from a fetch

Currently, I am successfully fetching data from an API and storing it. However, I now want to incorporate a functionality where a user can paste a website URL into an input box, click a button, and then display the results in a return div UI. I am struggli ...

What is the best way to smoothly insert an item into a nested object within the state of a React component

Trying to create a complex array using react hook: const [strategy, setStrategy] = useState([leg]); Here's how the `leg` object is defined: const leg = { entry: { conditions: [], actions: [""], }, exit: { conditions: [], ...

Save information in a session using html and javascript

I'm having trouble accessing a session variable in my javascript code. I attempted to retrieve it directly but ran into issues. As an alternative, I tried storing the value in a hidden HTML input element, but I am unsure of how to properly do that wit ...

What could be causing my directive to not display the String I am trying to pass to it?

Currently attempting to create my second Angular directive, but encountering a frustrating issue. As a newcomer to Angular, I have been studying and referencing this insightful explanation as well as this helpful tutorial. However, despite my efforts, I am ...

Issue encountered while attempting to remove a row from a table (JavaScript)

I'm encountering an error when attempting to delete a table row: "Uncaught ReferenceError: remTable is not defined index.html:1:1". When I inspect index.html to identify the issue, I find this: remTable(this) This is my code: const transact ...

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

Generating progress bar in Javascript while exporting CSV fileCan JavaScript export CSV and

Looking for a way to add a progress bar while generating and serving a CSV file via ajax? The database-heavy process is causing a delay, so I need a loader on the screen that disappears once the task is complete. It should be done with ajax or stay on th ...

Next.js is perplexing me by throwing an error about Event handlers not being able to be passed to Client Component props, even though the component clearly has "use client" at

My bundler generates a basic React component like this "use client"; "use strict";var a=Object.create;var r=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,s=Objec ...

Steps for Removing Multiple CSS Styles from an Element's Style:

When my application generates inline styles, I sometimes need to remove the height, width, and max-width styles from certain elements. I have identified the element using this code: const elems = window.$('.myElements'); window.$.each(elems ...