Leveraging setters in JavaScript for modifying properties

The MDN documentation for the set function appears to suggest that a setter defined in [ECMAScript 2015] should not exist in an object literal alongside a data entry for the same property.

[ECMAScript 2015] setter must not appear in an object literal ... with a data entry for the same property.

However, this rule seems to change when employing the super keyword.

class Foo {
    constructor(bar){
        this.bar = bar
    }

    set bar(newBar){
        if (!newBar.match(/\w+/))
            throw Error("Invalid bar value")
        // Despite not being a derived class, I can still use 'super'.
        return super.bar = newBar
    }
}
const baz = new Foo("Baz")
baz.bar = "new value" // No recursion

This feature is advantageous as it eliminates the need to conceal the property by adding an underscore prefix. It also avoids altering the property enumerability to prevent the hidden version from appearing in loops or serialization processes.

Nevertheless, the set syntax can be somewhat obscure, making it challenging to understand its exact functionality.

Am I violating any rules by utilizing this method, or is it acceptable?

Additionally, what does the usage of super signify here?

Answer №1

This feature may seem helpful since there is no need to hide the property by adding an underscore or similar prefix. It also eliminates the need to adjust property enumerability to prevent the "hidden" version from appearing in loops or serialization.

However, this approach is not as useful as it seems. It can be considered a hack at best and does not function as expected.

In reality, there is nothing concealed here. By creating a new instance property named bar, you are essentially overshadowing any getters/setters defined on the prototype. The second assignment will not trigger your setter. Additionally, the instance property created is a standard enumerable property, so it will appear in loops and during serialization.

What exactly does "super" reference in this context?

The keyword super points to the object's prototype where the method (or setter) is defined, represented by

Object.getPrototypeOf(Foo.prototype)
. In this scenario, it would be the Object.prototype since your class Foo does not extend anything.

When accessing .foo, it searches within that prototype and typically finds an inherited method from the parent class. Yet with super.foo, the operation's receiver becomes the current instance of this rather than the prototype.

In your case, although it's not invoking a method but performing an assignment, it could activate a setter inherited from the parent class. Since there is no Object.prototype.foo property present, it defaults to a regular assignment on the target - which happens to be the instance itself as baz, resulting in a new own property creation.

Therefore, using this technique is not recommended.

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

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Searching for and deleting Redis data: A step-by-step guide

I'm currently utilizing the redis-om npm library to interact with Redis, and I've come across a method for removing a single key: const {Client, Entity, Schema} = require('redis-om'); .... await this.repository.remove(<key>) Howe ...

Troubleshooting objects in Javascript: Understanding the scope problem with 'this'

Here is my code snippet: var tradingInterface = function() { this.json = ''; this.init = function() { $.get( '/whatever',{}, function(data) { this.json = data; // Rebuilds Everything ...

struggling to navigate the request to a different HTML page from the controller using AngularJS

Having a situation where I need Page A to render Page B with the values entered on Page A upon submission. Page A is connected to controller A, and when the click event triggers, the Spring controller renders Page B. The problem I'm encountering is t ...

Guide on utilizing a variable as a property in the `indexOf` function within a `map` function

I have a method that looks like this: retrieveUniqueValues(param) { var uniqueValues = []; uniqueValues = this.state.DataObjects.map(item => { if (uniqueValues.indexOf(item[param]) === -1) { uniqueValues.push(item[param]) ...

The resolution of all elements following an async/await within an Array.map() operation may not be guaranteed

In a previous post, I asked a question about running synchronous functions as promises. After converting them to asynchronous functions, the output now displays some null elements in the array. I am puzzled as to why this is happening. Here is a snippet o ...

encasing a container element around every trio of elements

I'm currently working on grouping every 3 divs with a class of search-audio inside a div with a class of slide. The issue I'm facing is that it's giving me an error stating that elem.parentElement is undefined... However, the initial part ...

Developing JavaScript entities for manipulation controls

Currently, I am developing a customized WebControl that incorporates AJAX features. This control is built upon the System.Web.UI.WebControls framework and includes the registration of control-specific JavaScript using ClientScript.RegisterClientScriptReso ...

Sorting or filtering with two elements in the option value in AngularJS

I have been struggling for a while now to find a solution to this issue. How can I display the query for the third option value, which should show the filter of DB || CSLB from a json file? <select ng-model="search.source"> <option value="DB"& ...

Restrict certain links from being clickable until the page has finished loading and all click events have been bound using

I developed a modal dialog plugin using jquery, designed to link to the click event of each <a> element with a specific class. This modal dialog uses AJAX to 'fetch' a page declared under the 'href' parameter of the <a> el ...

JavaScript - Struggles with developing a personalized AJAX function

I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response. The function in question is named ajaxPost(paramArray, target). It takes param ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...

Implementing Rule for Password Matching in Bootstrap 4 Form Validation

I am utilizing Bootstrap 4 / JS form validation (https://getbootstrap.com/docs/4.0/components/forms/#custom-styles) and it is functioning as expected. Currently, I am working on implementing the same style and submission rules for comparing two password f ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

The $size property in mongoose is always returning zero for me

Hello, I've encountered an issue where the $size property in my aggregate query always returns 0 after adding $addFields. Below are the details of my tables and query: Table: post { _id: 1, text: 'some text', } Table: comments { _id: 1, te ...

Troubleshooting issues with Javascript ES6 module functionality

I'm struggling to solve a problem with my small app setup. In my project, I have an index.html file that includes a javascript file and another file named myJsModule.js in the same directory. Here's the code inside myJsModule.js: export default ...