JavaScript Object's Property Cannot Be Read

I am experiencing an issue with the read value of my property not functioning correctly. It is displaying the object name as a string rather than the actual property of the object.

My goal is to create an object and set its properties based on the object's name.

After setting the properties, I want to view them using a loop. The method "this.propertyname" is working fine for me.

    function building(buildingType)
{  
    console.log("In main function");
    this.room = 2;
    this.clr = "green";
    this.scrn = null;

    getType();

    function getType()
    {  
        console.log("In control function");
        switch (buildingType){
            case "home":
                setBuildingAs(2, "green", null);
                break;

            case "office":
                setBuildingAs(20, "white", null);
                break;

            case "mall":
                setBuildingAs(200, "assorted", null);
                break;

            case "theater":
                setBuildingAs(20, "white", "78cm");
                break;

            default:
                console.log("Please Enter Valid Type");
                break;
        }
    }

    function setBuildingAs(noOfRooms, buildingColor, theaterScreen){
        this.room = noOfRooms;
        this.clr = buildingColor;
        this.scrn = theaterScreen;
        valueGetter(this);

    }

}

function valueGetter(obj){
  for(var key in obj)
  {     
    console.log(key + " has value of " + obj[key]);       


  }
} 


console.log("In Script");

var house = new building("home");

var house2 = new building("mall");

var house3 = new building("theater");

Unfortunately, the valueGetter function is not providing me with the desired output of all property values.

Answer №1

Your response has been customized and below is the outcome:

    function constructing(structureType)
{  
    console.log("Inside primary function");
// It is crucial to declare "this" in the global scope (as it is different within the setStructure method!)
    var myself = this;
// Assigning all properties to variable "myself"
    myself.room=2;
    myself.color = "green";
    myself.screen = null ;

    getDesign();

    function getDesign()
    {  console.log("In control mechanism");
        switch(structureType){
            case "home":
            setStructure(2,"green",null);
            break;

            case "office":
            setStructure(20,"white",null);
            break;

            case "mall":
            setStructure(200,"assorted",null);
            break;

            case "theater":
            setStructure(20,"white","78cm");
            break;

            default:
            console.log("Please Enter a Valid Type");
            break;

        }
    }

    function setStructure(numOfRooms,buildingColor,theaterScreen){
        myself.room=numOfRooms;
        myself.color=buildingColor;
        myself.screen=theaterScreen;
// Invoking the value retriever with the local object "myself"
        valueRetriever(myself);

    }


}

function valueRetriever(obj){
  for(var key in obj)
  {     
    console.log(key + " holds a value of "+obj[key]);       


  }
} 


console.log("In Script");

var home1 = new constructing("home");

var home2 = new constructing("mall");

var home3 = new constructing("theater");

Check out the updated code on jsFiddle here: http://jsfiddle.net/yWF9B/

Answer №2

Example showcasing the use of ECMA5 Function.prototype.bind

(as well as some other ECMA5 methods just for fun)

Exploring the usage of the this keyword.

Javascript

// Placed here to define things before usage.
function valueGetter(obj) {
    // Utilizing ECMA5 methods for demonstration
    Object.keys(obj).forEach(function (key) {
        console.log(key + " has a value of " + this[key]);
    }, obj);
}

// Preferring to start constructors with a capital letter
function Construction(constructionType) {
    console.log("Inside main function");
    // Changed to function expression and removed name from function
    var setConstruction = (function (numberOfRooms, constructionColor, cinemaScreen) {
        this.room = numberOfRooms;
        this.clr = constructionColor;
        this.scrn = cinemaScreen;
        // Displaying 'this' content instead of 'constructionType'
        console.log(constructionType);
        valueGetter(this);
    }).bind(this); // added the bind

    this.room = 2;
    this.clr = "green";
    this.scrn = null;
    getType();

    function getType() {
        console.log("In control function");
        switch (constructionType) {
            case "home":
                setConstruction(2, "green", null);
                break;
            case "office":
                setConstruction(20, "white", null);
                break;
            case "mall":
                setConstruction(200, "assorted", null);
                break;
            case "theater":
                setConstruction(20, "white", "78cm");
                break;
            default:
                console.log("Please Enter Valid Type");
                break;
        }
    }
}

console.log("In Script");
// Using one 'var'
var house = new Construction("home"),
    house2 = new Construction("mall"),
    house3 = new Construction("theater");

Output

In Script
Inside main function
In control function
home
room has a value of 2
clr has a value of green
scrn has a value of null
Inside main function
In control function
mall
room has a value of 200
clr has a value of assorted
scrn has a value of null
Inside main function
In control function
theater
room has a value of 20
clr has a value of white
scrn has a value of 78cm 

On jsFiddle

An alternate approach could have been to utilize an object-oriented method and create a prototype.

Javascript

// Written here to define things prior to usage.
function valueGetter(obj) {
    // Utilizing ECMA5 methods for demonstration
    Object.keys(obj).forEach(function (key) {
        console.log(key + " has a value of " + this[key]);
    }, obj);
}

// Preferring to start constructors with a capital letter
function Building(buildingType) {
    console.log("Inside main function");    
    this.room = 2;
    this.clr = "green";
    this.scrn = null;
    this.buildingType = buildingType;
    this.getType();
}

Building.prototype = {
    setBuilding: function (numberOfRooms, constructionColor, theaterScreen) {
        this.room = numberOfRooms;
        this.clr = constructionColor;
        this.scrn = theaterScreen;
        // Displaying 'this' content instead of 'buildingType'
        console.log(this.buildingType);
        valueGetter(this);

        return this;
    },

    getType: function () {
        console.log("In control function");
        switch (this.buildingType) {
            case "home":
                this.setBuilding(2, "green", null);
                break;
            case "office":
                this.setBuilding(20, "white", null);
                break;
            case "mall":
                this.setBuilding(200, "assorted", null);
                break;
            case "theater":
                this.setBuilding(20, "white", "78cm");
                break;
            default:
                console.log("Please Enter Valid Type");
        }

        return this;
    }
};

console.log("In Script");
// Using one 'var'
var house = new Building("home"),
    house2 = new Building("mall"),
    house3 = new Building("theater");

On jsFiddle

If not in an ECMA5 environment, shims are available on MDN or you can use the ES5 shim library. Alternatively, modern JavaScript libraries offer functional equivalents to .bind.

For example:

  1. lodash/underscore, _.bind()
  2. jQuery.proxy
  3. dojo.hitch

You could also employ a closure to circumvent the issue, or even utilize call or apply.

idiomatic.js 6B by R.Waldron

As a last resort, create an alias to this using self as an Identifier. This is extremely bug prone and should be avoided whenever possible.

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

Rearrange the elements in an array containing objects

I am working with an array of objects: const array = [ { id: "5a2524432b68c725c06ac987", customOrder: 1, name: "One", }, { id: "5a2524432b68sgs25c06ac987", customOrder: 2, name: "Two", }, { id: "5a252wfew32b68c725c06a ...

JQuery enables nested sorting functionality

I need to enable the sortable feature specifically for the charts. Index.cshmtml <div id="sortable" class="col-lg-9"> <div class="col-lg-12 col-md-12 padding hidden" id=@($"chartNumber{Model.Charts[ ...

Is there a way to execute JavaScript tests by incorporating debugger statements?

There isn't a one-size-fits-all solution to this question, and it hasn't been addressed on Stack Overflow either. My background is in Python, where I can use import pdb; pdb.set_trace() to debug code step by step with a debugger. How can I achiev ...

The most effective way to initiate an action following a popup

Here's a button that triggers the opening of a popup: <button type="button" id="btnBuscarCuenta" onClick="javascript:AbrirPopUpBusqueda('id_AyudaCuentas', 'pop_cuentas_contables.cfm','', '900px&a ...

Compiling angular and ngrx: errors when tap() is removed

I have a snippet of code (slightly simplified) that is functioning correctly and the console logs are displaying everything properly, with valid parameters passed: return observable.pipe(map(response => ({ response, param2, param3, param4, param5 }))) ...

Retrieve an HTML element that is a select option with jQuery

I have a select input containing different options as shown below: <select id="myArea"> <option class="myClass_1" style="color:red;" value="1">Area 1</option> <option class="myClass_2" style="color:green;" value="2">Area 2& ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

Clicking an element to uncover more information

Currently, I am working on solving the second question within this series of problems. The task involves creating a functionality where clicking on a legislator's name displays additional information about them. You can view my progress so far by visi ...

Unraveling a JSON array in PHP

Having trouble decoding a JSON object in PHP that is received from a JavaScript page? Here's how you can decode the JSON and store it in PHP such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in PHP. after removing "myString ...

Node.js - Request timeout issue: Headers cannot be set after they have already been sent

My node.js app is running with mongoose, express, mongodb. I have a 'team' page that displays teams from the database. Everything was working fine until I added the code below. Now, when I navigate to the page and refresh it or try to load it aga ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...

creating a one-to-one relationship between two arrays in angular

students:any=[{name:'shariful', id:'1',teacherId:'1'},{name:'Hasan', id:'2',teacherId:'2'},{name:'sohag', id:'3',teacherId:'2'}] teachers:any=[{name:'Robi', ...

Issue with React-select: The background color is not extending to the full width when using wordWrap:"scroll"

I am currently implementing react-select in one of my projects. I need the wordWrap property to be set to "scroll". However, when the length of the options exceeds the menu width and I scroll to the right, the hover color does not fill the entire width. T ...

Extending the href value using jQuery at the end

Can someone help me with this link: <a id="Link" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745425453424b4b524940674e0a4355464e4909494253">[email protected]</a>?subject=I-Drain Bestellung& ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

In this JavaScript tool for counting characters, every carriage return is counted as two characters

Hello there! I have created a character counter in JavaScript that looks like this: <textarea class="SmsText" id="txttemplate" maxlength="160" /> <span id="charsCount">160</span></strong><span>character(s) left</span> ...

Refreshing a Thymeleaf table dynamically without having to reload the entire page

I am currently using the Thymeleaf attribute to render data, but I am now looking to add a "Search" button without reloading the page. Within the attribute departments, I am rendering a List<Department> from the database. While I understand how to a ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

Change the class upon clicking the element

Looking to create a function that toggles classes on elements when specific links are clicked. For example, clicking on link 1 should add the "active" class to the red element, while clicking on link 2 should do the same for the pink element, and so forth. ...