Exploring the ins and outs of building JavaScript objects using constructors

When creating a new object with var obj = new Object(value); and assigning property values with obj.value = newValue, I encountered an issue where only one of these actions would work at a time. Is there a way to make both work within the same object declaration?

In the code snippet below, I aim to only receive Boolean values. If a non-Boolean value is provided, I want to default to true.

/*
* why does this work on instantiation but not on property assignment?
*
*/

var robot = function(isAlive) {
    this.isAlive = (typeof isAlive === 'boolean') ? isAlive : true; // why does this work on instantiation but not on property assignment?
};

bot4 = new robot(true);
bot5 = new robot("random string");

bot4.isAlive = "random string";
console.log("bot4: " + bot4.isAlive); // -> random string
console.log("bot5: " + bot5.isAlive); // -> true



/*
* why does this work on property assignment but not on instantiation?
*
*/

var android = function(isAlive) {
  Object.defineProperty(this, "isAlive", {
    get: function() {
      return isAlive;
    },
    set: function(value) {
      isAlive = (typeof value === 'boolean') ? value : true; // why does this work on property assignment but not on instantiation?
    }
  });
};

droid1 = new android(true);
droid2 = new android("random string");

droid1.isAlive = "random string"; // note the string assignment failed and is assigned the default value of true
console.log("droid1: " + droid1.isAlive); // -> true

droid1.isAlive = false; // passed since this is boolean
console.log("droid1: " + droid1.isAlive); // -> false

console.log("droid2: " + droid2.isAlive); // -> random string

View on JSFiddle

Answer №1

If you want both functionalities to work together, make sure to set the property in the constructor after it has been defined like this:

var device = function(onlineStatus) {
  Object.defineProperty(this, "onlineStatus", {
    get: function() {
      return onlineStatus;
    },
    set: function(value) {
      onlineStatus = (typeof value === 'boolean') ? value : true; // This code snippet works on assigning a new value to the property but not during instantiation. Why?
    }
  });

  this.onlineStatus = onlineStatus;
};

Code Sample

Answer №2

The issue with the first approach is that updating the "isAlive" property of an already instantiated object will only make the assignment but won't trigger the constructor code. The constructor code executes only when the object is created.

On the other hand, the second example works as expected. However, it has a limitation where the setter function only accepts boolean values. If you try to assign a string to the "isAlive" property, the setter will still set the value to true.

It's important to note that the "isAlive" parameter in your constructor function is distinct from the "isAlive" property of the object that gets created.

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

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

Set up a timed event for a .js file to execute

I am currently exploring options for automatically running a JavaScript file multiple times per day, similar to Task Scheduler on Windows. Right now, I manually run the file in VS Code or Command Prompt using the command "node file.js". Is there a way to a ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

The array of objects has vanished into thin air

I am receiving a JSON string from my server through a PHP file, which contains 25 meals. The PHP script is initiated by a JavaScript function. My goal is to convert the JSON into an array of objects. The response stream displays the correct values and eac ...

Issue: Module 'blog' not found in the specified path in my Node.js application

this snippet showcases my code in routes/blog.js var express = require('express'); var router = express.Router(); const Blogs = require("../models/blog"); and here is the code from models/blog.js const mongoose = require('mongoose ...

Having trouble with jsPlumb accurately rendering lines

http://jsbin.com/ofapew/1/edit I am currently experimenting with jsPlumb to connect two points, specifically trying to link the green dots to the top of a black border box. One thing that is puzzling me is that even though the green dot end point appears ...

What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array. As I iterate through the elements of the array, I am checking the values associated with the key "type ...

Invoke a specific script snippet by its identifier within a React single-page application, causing the content to appear only upon manual

I am currently working on a React application that utilizes a third-party JS script from OneTrust cookie scripts. Unfortunately, the scripts provided are not optimized for single-page applications (SPAs). At the moment, I am simply referencing the script s ...

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

The reason for the undefined socket.id in the browser is due to a potential

When using console.log(socket), I am able to see a socket object in Firebug. Within this object, there is a property called id and I can view the value of this id. However, when I try to access it directly with console.log(socket.id), the result is undefin ...

Can you save or transfer a localStorage JSON file to your computer's hard drive?

I am utilizing an AngularJS schedule app and I am interested in finding a method to save the changes made within the app to disk when it is closed. Upon reopening the app, I would like it to retrieve the updated data from the JSON file. Storing data in lo ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

Refine the Vuex state with a filter

Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management. In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iter ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

I am encountering a JQuery syntax error while using Bootstrap 3 button-dropdown links

I'm trying to replicate the example found here in order to create a similar markup: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ...

The content within Contentful is presented in a JSON object format, but accessing specific values is proving to be

I have successfully added two records in the contentful database and now I am attempting to fetch the content from Contentful into my React-hooks website. However, I am facing difficulties retrieving the values for title, description, image, and shortDescr ...

Creating a multi-filter gallery similar to the one found in WooCommerce or eCommerce platforms involves integrating various filters to allow

Looking for a dynamic multifilter gallery similar to WooCommerce/ecommerce product filters? We have three types of filter dropdowns: COLOR, SIZE, and SHAPE. For example, if you select color: red and green, size: small, and shape: round The filtering wil ...

Updating the progress state of MUI linear determinate diligently

I currently have a modal set up that handles some asynchronous logic for submitting data to a database. The component I am using, called LinearDeterminate, is designed using Material-UI. You can find more information about it here: MUI Progress import { u ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...