Features of ES2015's [[class]] attribute

I've been developing a basic clone function

var shallowCopy = function (value) {
  // In ES2017, we could also use
  // return Object.create(Object.getPrototypeOf(value), Object.getOwnPropertyDescriptors(value));
  let propDescriptors = {};
  for (let i of Object.getOwnPropertyNames(value)) {
    propDescriptors[i] = Object.getOwnPropertyDescriptor(value, i);
  }
  return Object.create(Object.getPrototypeOf(value), propDescriptors);
};

I have noticed that

Object.prototype.toString.call(shallowCopy([]))
returns [object Object] instead of [object Array].

However, I find the behavior of some new types introduced in ES6 intriguing

Object.prototype.toString.call(shallowCopy(new Set())) // [object Set]
Object.prototype.toString.call(shallowCopy(new Map())) // [object Map]

Does anyone know why these objects exhibit different behavior?
Do you think this behavior will change in the future?

Thank you.

Answer №1

This particular item is not classified as a set. Genuine sets possess internal [[SetData]] slots that cannot be duplicated.

shallowCopy(new Set()).add(123); // TypeError: add method called on incompatible Object

In essence, relying on the [[Class]] property to determine the type of object you're dealing with is not advisable. Interestingly, the [[Class]] feature no longer exists in ES6.

Answer №2

Your actions do not seem to be linked to the [[Class]] of an object.

If you check the output of Map.prototype, you will notice that these new variations come with a toStringTag Symbol:

> Map.prototype
Map {Symbol(Symbol.toStringTag): "Map"}

This Symbol property determines the string representation generated by calling toString(). Refer to Symbol.toStringTag on MDN for more information:

It provides a default description for objects, which is utilized by Object.prototype.toString().

The behavior is unlikely to change for older ES6 types due to compatibility concerns.

Answer №3

One important aspect of a Specification is the special symbol known as @@toStringTag, which is utilized when constructing the string representation of an object. To learn more about this symbol, refer to the Well-Known Symbols section, where it specifically explains @@toStringTag.

@@toStringTag is a String-valued property that contributes to creating the default string description of an object. This property can be accessed using the built-in method Object.prototype.toString.

If you examine the values of @@toStringTag for various types like Set or Promise, you will find interesting information. For example, the value for Set is defined in 23.2.3.12 Set.prototype [ @@toStringTag ]:

The initial value of the @@toStringTag property is the String value "Set".

Feel free to explore other types such as Promise (25.4.5.4), ArrayBuffer (24.1.4.4), and more.

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

Displaying infowindow pop-ups on random markers on Google Maps every 3 seconds

Here lies the challenge. I am tasked with creating a Google map that displays multiple markers. Each marker must have a unique info window with distinct content. Upon opening the website, an info window randomly appears on one of the markers after 3 sec ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

React is currently in the process of downloading images that were not fetched during

(Update: Initially, I suspected React Router was the cause of this issue. However, after eliminating React Router from the codebase, the problem persists. Therefore, I have extensively revised this inquiry.) Situation: I am dealing with paginated pages th ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

Is it feasible to activate a function when certain Vue data elements are altered?

Looking to monitor a set of data elements for changes and then save them in localStorage. Is there an easy way to achieve this? ...

Using jQuery to assign a specific value to all select boxes

I am facing a challenge where I need to change the values of all select boxes on my page to a specific number. Here is the HTML structure: <select> <option value="-1" <option value="55">ENABLE</option> <option value= ...

Testing a directive that has templates all contained within a single file with script tags

I'm struggling to include my directive's templates in my Karma unit tests. The templates are all in one file within different script tags. The error message I encounter is: PhantomJS 1.9 (Linux) ERROR SyntaxError: Parse error at /var/www/html ...

The next and previous buttons on the JQuery UI datepicker are related to only one ancestor. When using $(e.target).parents(), it will only return a

Unfortunately, my reputation isn't high enough to post my own answer just yet. However, I wanted to share it before wasting more people's time: I finally figured out why I was not getting all the expected ancestors: The JQuery datepicker actuall ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

Ways to customize a bot's status based on the time of day

I'm currently working on enhancing my discord bot by having its status change every hour for a more dynamic user experience. However, I'm facing challenges with JavaScript dates. Can anyone provide some guidance? Below is the snippet of code I ha ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

The Vue JS Router is prominently displayed in the center of the webpage

I have been delving into Vue JS and working on constructing an app. I've implemented vue router, however, it seems to be causing the content within the routed component to display with excessive margins/padding. I've attempted various solutions s ...

Converting HTML to JSON using jQuery

Currently, I am utilizing the jQuery template plugin to dynamically create HTML based on JSON data that user can then modify (and even change). My goal is to find a way to convert this HTML back into JSON format so that it can be saved back to my server. ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

What method can be used to incorporate Google Places API into a .js file without using a <script> element?

As I delve into the Google Places API documentation, I noticed that they require the API be loaded in this format: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Is ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...