"employing" the extent and characteristics using square brackets for notation

Can we access object properties that can only be accessed with square bracket notation while inside a "with" statement?

For instance:

var o = { "bad-property": 1, "another:bad:property": 2, "goodProperty": 3 };

with(o) {
    console.log(goodProperty); // works great
    console.log(???) // how do we access the "bad:property"?
}

Answer №1

It's amazing how time flies, but the information provided here is incorrect. However, there is indeed a solution to achieve your desired outcome.

with({'!@#$%': 'wowza', d: 'hello'}) {
  console.log(d); //hello - of course
  console.log(valueOf()['!@#$%']); //wowza - WOWZA
}

Did you catch it? valueOf() holds the key. This function retrieves the primitive value of its parent object, or the object itself if no primitive value exists. Every object and object-like primitive includes this method, as it is an inherent property of Object.prototype. So...there you have it.

Answer №2

Typically, the with keyword is employed to simplify long namespaces, rather than simply referencing a single object. The purpose of utilizing the keyword in this context isn't clear to me. It's unlikely that the syntax parser will accept o.bad:property, as it appears to be attempting to do in the code using with.

If the o object in this scenario is merely a shortcut for a lengthier namespace, I would suggest stopping one step shy in the resolution process using with. Instead, you could encapsulate your property within a string like so...

var nmSpace = new Object();
nmSpace.o = { "bad:property": 1, "goodProperty": 2 };

with (nmSpace) {
    alert(o['goodProperty']); // functions perfectly
    alert(o['bad:property']);  // now accesses "bad:property"!
}

I hope this explanation proves helpful.

Answer №3

In my understanding, when using with(o), it allows you to directly access properties of object o by their name, such as "bad" and "goodProperty".

with(o) {
  bad = "updated value";
  goodProperty = 22;
}

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

AngularJS confirmation directive for deleting items

I am currently utilizing this directive for a confirmation prompt when deleting an app. However, regardless of whether I click cancel or yes, the app still gets deleted. <small class="btn" ng-click="delete_app(app.app_id)" ng-show="app.app_id" ng-con ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...

receiving onPaste or onChange events within a component that generates input fields

My goal is to achieve the following functionality: <MyTextInput onChange={console.log("Change")} /> This particular component serves as a container for <input type="text" /> without triggering any action when text is typed (the purpose of usi ...

How can I transmit a pong frame using WebSocket in javascript/NodeJS?

I am struggling to locate a proper example demonstrating how to send a PONG response using javascript/NodeJS within the context of a WebSocket connection (back to a server that requests it after sending a PING request). Can anyone provide guidance on thi ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...

Incorporating an HTML page into a tab through Ajax with the help of a for loop, utilizing Bootstrap 3

Currently, I am developing an Address Book application where the main page displays a series of tabs with the names of the contacts from the contact.objects using a for loop in the code below. How can I utilize ajax to load the information of each contact ...

A unique technique for creating a stunning visual effect with images using

Can anyone help me with this issue: Check out this animated GIF The images in my project are overlapping when scrolling! How can I achieve a similar effect for my images? Is there a tutorial or plugin available for this? Here is the current code sn ...

Typescript encountered an error indicating that the property "x" is nonexistent on the specified type of 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'

I recently started using Typescript with Nextjs and encountered an error while trying to typecheck a basic component. How can I resolve the error and typecheck my array of objects? ERROR in C:/Users/Matt/sites/shell/pages/index.tsx(22,4): 22:4 Property &a ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

Avoiding remote submission in Grails forms: Best practices

<g:formRemote name="form1" update="homeBody" url="[controller: 'xxx', action:'aaa']"> <Button type="submit">Save</Button> </g:formRemote> I am facing a scenario where I need to place a text field o ...

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

Firefox failing to trigger key events within iframe

For fun, I created my own little JSFiddle website where I built a Snake implementation that works great in Chrome. However, when I try to use it in Firefox, I can't control the player with the arrow keys or WASD. You can check it out here: I read on ...

Utilizing Google Places Autocomplete to tailor search outcomes

I'm currently working on customizing the output of my Google Places autocomplete code. Specifically, I want to change the displayed result when a user selects an address from the list. For example, one of the results is: '45 Alexandra Road Holi ...

Ways to duplicate the content of a div to the clipboard without the use of flash

Simple question! I have a div identified as #toCopy, along with a button identified as #copy. Can you suggest the most efficient method to copy the content of #toCopy to the clipboard upon clicking #copy? ...

Refresh your textarea content using the replace method in jQuery

My goal is to extract and manipulate specific values within a user-entered code using jQuery. The code includes custom tags called setting, which I want to extract and display in input fields for easy editing. I have successfully retrieved and displayed th ...

What is the best way to communicate between the Browser and WebDriver using Protractor?

As I work on integrating Protractor for running tests on my Angular web application, I leverage a custom Angular service called ApiClient for making API calls. To mock this service, I utilize browser.addMockModule along with angular.module().factory(). Thi ...

Could you show me how the easyrtcid is generated in the demonstration of audio-only chat? I would appreciate a step-by

Currently, I am utilizing the easyrtc webpage to test out the audio only chat demo and everything seems to be running smoothly. However, when connecting, the easyrtcid variable is automatically assigned a random string. I was wondering if there is a way t ...

retrieve scanned image information with node.js

Hey, I'm currently dealing with an issue that involves a form containing various types of questions such as boolean and text field answers. The user fills out the form, scans it, then uploads it to a node.js server. The node server will extract answe ...

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...