Contrasting results between Object assign and Object spread

In my TypeScript code, I am compiling to ES2016 and encountered a situation where I was calling two different functions with similar this objects using Function.prototype.call(). To merge both this objects, I decided to use a common object and utilized the ...spread syntax like this:

let selfShared = {
  props,
  // ...
};

let selfHost = {
  ...selfShared,
  // ...
};

let selfGuest = {
  ...selfShared,
  // ...
};

The intention behind using spread was to be able to overwrite shared properties in either of the this objects if needed. However, when compiled by tsc, it resulted in unexpected behavior as shown below:

let selfShared = {
  props
};

let selfHost = Object.assign(Object.assign({}, selfShared), {
  // ...
});

// ...

By incorporating my initial code snippet:

let state = undefined;
let attributes = {};
let selfShared = {
  props: attributes
};

let selfHost = {
  ...selfHost,
  get state() {
    console.log("selfHost get state");
    return state;
  },
  set state(originalStates) {
    console.log("selfHost set state");
    !state ? state = originalStates : console.error("`this.states` already defined in the host function.");
  }
}

The output showed a difference between the expected result and the actual result after compilation by tsc. This discrepancy led to different logs being displayed based on the execution environment.

Furthermore, I tried moving the spread operation to the end of the file, which produced a correct output but limited my ability to override properties from selfShared.

If you can shed some light on why these discrepancies occur with Object.assign and provide any tips to achieve the desired outcome after compilation by tsc, it would be greatly appreciated.

Answer №1

When utilizing the spread operator

let obj = {
  ...otherObj,
  // ...
}

or

let obj = Object.assign({}, otherObj, {
  // ...
})

The spread operator is treated as literal, which means that properties are interpreted as strict values. This results in normal values being read normally, setters being ignored, and getters being read as normal values.

Setters and getters function as intended when the spread operator is placed at the end like so:

let obj = {
  // ...
  ...otherObj
}

or

let obj = Object.assign({
  // ...
}, otherObj)

as otherObj only extends the unique objects.

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

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

What is the trick to displaying Bootstrap 5 dropdown arrows when the button label is lengthy?

Within a fixed-width element, I have a Bootstrap dropdown which causes the arrow to disappear when the button text is too long. Is there a way to trim the text while still displaying the arrow, similar to this image: https://i.sstatic.net/jHp5R.png .ou ...

Can someone assist me with arranging these divs within my flexbox layout?

I'm having a tough time figuring out why the flex box aspect is making things so complicated for me. My goal is to achieve responsiveness like this - https://i.sstatic.net/MdzPO.png Despite following various flex tutorials, I haven't been succe ...

Animating images on scroll using Bootstrap's utilities

Is it possible to use bootstrap for creating a responsive animation of a bicycle moving from start to end as the user scrolls down the page? Additionally, how can I incorporate a responsive dotted line using bootstrap as well? Are there any codepen exampl ...

Angularjs: a powerful tool for passing data efficiently between controllers

In my angular.js application, I have implemented multiple views and I am in need of maintaining the status across view changes. To achieve this, I have created a simple factory to share data between controllers. Instead of using "$scope" in the controllers ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

Using the model's value as the name for another model in AngularJS

var app = angular.module('LoginApp',[]); app.controller('dynamicController', ['$scope', function($scope) { $scope.role= "Admin"; $scope.auctionNumber = 1; $scope.itemsArray = [{ letter:"a" , number:1 }]; }]); To d ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...

Find the viewport dimensions of the browser using Javascript and display them in the body CSS

Currently utilizing Andy Langton's JavaScript to retrieve my viewport size. If you're unfamiliar with it, check out the link below: The script is functioning as expected, but I'm uncertain of the optimal method for having the script output ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

Is there a way to change the domain for all relative URLs on an HTML page to a different one that is not its current domain, including in HTML elements and JavaScript HTTP Requests?

I am dealing with a situation where my page contains "domain relative URLs" like ../file/foo or /file/foo within a href attributes, img src attributes, video, audio, web components, js ajax calls, etc. The issue arises when these URLs need to be relative ...

JavaScript code failing to return array contents

As I navigate through the realms of NodeJS application development handling .nessus result files, I encounter an intriguing behavior quandary when generating an array of numbers. The primary goal is to create an array [1234,1223,1222] from a "results" file ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

What is the best way to establish a JavaScript function at the global level?

I need to make my function accessible globally in JavaScript. How can I accomplish this? Below is the function that I have: $(function () { function formatCurrency(input) { return input.toString().replace(/(\d)(?=(\d{3})+(?!\d) ...

Perpetual duplication of data occurs upon inserting an item into the Array state of a React component

Whenever a new item is added to the React JS Array state, data duplication occurs. console.log(newData) The above code outputs a single object, but when you print the actual data with console.log(data) You will notice continuous duplicates of the same da ...

Tips for extracting subdomains from URLs

Looking for a way to extract only the 'http://abc' part from a URL like http://abc.xyz.com, unfortunately getting the full 'http://abc.xyz.com'. I attempted using: windw.location.origin Do I need to implement an additional method to a ...

Dealing with delays in rendering certain values with Angular interpolation & ways to eliminate an element from an array of TypeScript objects

I am currently developing a web application using ASP.NET Core - Angular. The app allows users to select a customer as the starting point and then calculates the distance & duration to other customers using Google Maps Distance Matrix Service. Although I a ...

Using jQuery to add elements to another element

My goal is to create a button that, when pressed, will change the theme color on my jQuery mobile test site. Imagine my HTML parent div looks like this: <div id="firstPage" data-role="page"> I want to be able to click the button and have it add da ...

When using .slideup(), the entire ul is removed instead of just the nested li

Encountering some issues with this particular element: I am looking to ensure that when a hidden list collapses, the code checks to see if there are any other 'active' lists already open and closes them before opening a new one. It can be messy ...

`switch statement for handling different HTTP status codes`

I'm trying to implement a switch statement that returns an error message based on the http status code. Here's what I have so far: switch(true){ case err.status.test(/^4/): // 4xx res.fail(err.status, err); break; case err. ...