Is there a way to modify the value of a constructor key once it has already been defined?

I am currently working on a simple constructor exercise where I need to update a value after the constructor has been created. Even after changing the value to true, the cat is still not making its noise.

Challenge parameters

  • The constructor function will accept two parameters, raining and noise. These parameters will be assigned as values to keys within the constructor function.

  • Add a third key named makeNoise() which is a function. This function checks if the value of the raining key is set to true. If it is, then it logs the noise key's value in the console.

Bonus

  • How can we make the cat produce noise? In other words, how do we change the value of raining for the cat object after it has already been created?
function Animal(raining, noise) {
    this.raining = raining,
    this.noise = noise;

    this.makeNoise = function(){
        if(this.raining)
        console.log(noise)
    }
}
// Creating `dog` and `cat` objects with respective `raining` and `noise` properties
let dog = new Animal(true, 'Woof!');
let cat = new Animal(false, 'Meow!');

// Calling the `makeNoise()` methods on both the `dog` and `cat` objects
dog.makeNoise();
cat.makeNoise();

// BONUS CODE HERE
cat.raining= true;

Answer №1

To ensure that the sound is made, remember to invoke makeNoise() only after setting the raining property to true. If you call makeNoise() before updating the raining property, it will not log anything as JS executes (mostly) in sequence.

function Animal(raining, noise) {
  this.raining = raining,
    this.noise = noise;

  this.makeNoise = function() {
    if (this.raining)
      console.log(noise)
  }
}
// Instantiate `dog` and `cat` objects with `raining` and `noise` properties
let dog = new Animal(true, 'Woof!');
let cat = new Animal(false, 'Meow!');

// Invoke the `makeNoise()` methods on the `dog` and `cat` instances
dog.makeNoise();
cat.makeNoise();

// Additional code below for a bonus scenario
cat.raining = true;

cat.makeNoise();

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

Interactive Icon Feature Instead of Annoying Pop-Ups in JavaScript

Hello there! I need assistance fixing a code issue. Currently, the code automatically pops up when the page is opened. Is there a way to make it clickable instead of popping up automatically? <script type="text/javascript" src="//www.klaviyo.com/media/ ...

evaluation of three variables using short-circuit logic

I was quite surprised by the outcome of the code I wrote. It seemed like it wouldn't work because it was checking if something is not running and the ID matches a specific one, then executing the code regardless of the break size limit: if(!isRunning ...

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

Raycaster is unable to manipulate BoxMesh objects in any way

I've been working with the Physijs script for simulating physics, such as gravitation. I'm trying to use Raycaster from the THREE.js script to move objects within my scene. The issue I'm facing is that the Raycaster only moves objects (sim ...

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

What is the reason behind the lack of asynchronous functionality in the mongoose find method

Outdated code utilizing promises I have some legacy code implemented with mongoose that retrieves data from the database. The schema being accessed is AccountViewPermission. Everything works fine as I am using a .then, which essentially turns it into a Pr ...

Updating the Navigation Bar and Theme in CRM Dynamics 2013 to Reflect Your Organization's Branding

In my CRM Dynamics 2013 setup, I am faced with a unique challenge. I need to customize the Organization navigation bar based on which organization is currently loaded. Specifically, I have two organizations - QA and PROD. When a user switches to the QA org ...

How can I dynamically assign ng-model with a filter for a particular object in an array?

Is there a recommended method for linking an input element to a specific field of an object in an array using its id? I tried using ng-model along with the find() function from the array prototype. However, the implementation is not working properly as it ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

Setting default date and time for Bootstrap datetimepicker only in the expanded calendar view

Here is the setup: $(function () { $('#datetimepicker').datetimepicker({ defaultDate: moment(), sideBySide: true }); }); This configuration allows setting a default date & time when no value is provided for the f ...

Transforming a simple MySQL query into a structured nested JSON format

Is there a way to easily reorganize data without using complex for loops (perhaps with Underscore.js or refining the MySQL query)? I have data formatted like this: [ { "J_NUM": "BOAK-1212", "X_DUE_DATE": "2012-06-20T00:00:00.000Z", "X_LEAD_T ...

Exploring the World of D3.js with an Interactive Example

Struggling to grasp D3, I'm having difficulty executing the circle example. http://mbostock.github.com/d3/tutorial/circle.html I aim to run the part where the circles change colors and sizes. I simply copied and pasted the example but can't fi ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...

I am having trouble retrieving the array value from the response sent by my server

After receiving a dictionary from my server, when I try to access the values using the following code: {"filters":{ "Facture": [ "Магма (Тычок)", "Тонкий кирпич", "Гладк ...

Enhance Website User Experience: Keeping Track of Scroll Position When Users Navigate Back in Browser

Have you ever experienced the frustration of scrolling through a page with infinite scroll, only to click on a link and then go back to find that you've lost your place in the scroll? You're scrolling down a lot, You click on a link from the i ...

Executing Enter Key and Button Simultaneously with JavaScript: Step-by-Step Guide

I need assistance understanding how to simultaneously trigger the enter key and button in this code. When the value is entered into the input field, it should trigger both the enter key and the button "Enter" at the same time. Additionally, after pressing ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...