Creating JavaScript objects through function calls

let getBoxWidth = function() {
    this.width=2;
};

alert(getBoxWidth.width);

Hello there! Can you explain why the output is undefined in this scenario?

Answer №1

The reason for the need to include the "new" keyword in front of the function() is because that syntax creates a function, not a class. By using the "new" keyword, you are essentially treating the function as a constructor for a new object.

Check out this demo on jsFiddle: http://jsfiddle.net/afGTh/

var circleRadius = new function() {
    this.radius = 5;
};

alert(circleRadius.radius);​

Answer №2

One common method for constructing a javascript object is to use a defined function:

function RectangleArea(length) {
  this.length = length;
}

In general practice, constructors begin with an uppercase letter. Next, you can create an instance like so:

var ra = new RectangleArea(5);

alert(ra.length); // 5

If the object is simple enough, you could simplify it by doing this instead:

var ra = {length: 5};

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 on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

Implementing a return of a view from a Laravel controller function after an AJAX request

I'm currently working on a bookstore project where users can add books to their cart. Users have the option to select multiple books and add them to the cart. When the user clicks on the Add to Cart button, I store the IDs of the selected books in a J ...

Distinct elements within a JavaScript hash

Is there a jQuery method to add a hash into an array only if it is not already present? var someArray = [ {field_1 : "someValue_1", field_2 : "someValue_2"}, {field_1 : "someValue_3", field_2 : "someValue_4"}, {field_1 : "someValue ...

When the page loads, should the information be transmitted in JSON format or should PHP be responsible for formatting it?

I'm considering whether it would be more server-efficient and effective to send data to the user in JSON format upon page load, with JavaScript handling the conversion into readable information. For instance, when a user visits my index page, instead ...

Is it possible to modify variables in the controller when the route is changed?

My application utilizes a template and several views that are dynamically rendered based on their route: popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { ...

Issue with importing a library into a Next.js component

I seem to be facing an unusual issue with my Nav component. Although I am able to import various items in my other components without any problems, for some reason, I cannot import anything into my Nav component. import { useState, useEffect } from "r ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Utilizing the power of AWS Lambda in conjunction with moment JS to generate unique

My current time zone is GMT+8, and the AWS region I am using is Singapore (ap-southeast-1). I am facing an issue where there are discrepancies in date calculations between my local machine and when I deploy my code on AWS Lambda. My goal is to ensure that ...

Mesh in threejs does not include the customDepthMaterial property when outputting to scene.toJSON

I have been working on creating an object with the following code: const geometry = new THREE.SphereBufferGeometry(2,100,100); const material = new THREE.MeshPhongMaterial({ map: myImage, transparent: true, side: THREE.DoubleSide, opacity: ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

Having trouble uploading an image with Angular's HttpClient

Uploading an image using native fetch POST method works perfectly: let formData = new FormData(); formData.append('file', event.target.files[0]); console.log(event.target.files[0]); fetch('http://localhost:8080/file/ ...

Styling components using classes in Material-UI

I recently started using material-ui and noticed that it applies inline styles to each component. After running a test with multiple instances of the same component, I realized that there was no CSS-based styling - only repeated inline styles were generate ...

Enhancing IntelliJ IDEA's autocomplete functionality with JavaScript libraries

Is there a way to add my custom JavaScript library to IntelliJ IDEA 10.5 or 11 for autocomplete functionality? I want to specify that IDEA should recognize and suggest auto-completions for objects from my library. While it sometimes works automatically, ...

Properly configuring the root directory to troubleshoot Axios 404 POST issues within a Vue Component coupled with Laravel

As I delve into learning Vue+Laravel through a tutorial, I have encountered an issue with Axios when making an Ajax request within the script of a Vue Component. The console log error that is troubling me reads as follows: POST http://localhost/favori ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

What is the best way to display multiple modals in a React app?

I am facing a challenge where I need to render multiple modals based on the number of items in the 'audios' property of an object. Currently, I am using the mui modal library for this functionality. Here are the variables being utilized: const ...

What is the best way to apply a Javascript function to multiple tags that share a common id?

I am experimenting with javascript to create a mouseover effect that changes the text color of specific tags in an HTML document. Here is an example: function adjustColor() { var anchorTags = document.querySelectorAll("#a1"); anchorTags.forEach(func ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...