Tips on assigning a method from a class instance to any object using `Object.assign`

let myObject = {}

class MyClass {
  myFunction() {
    alert('hello');
  }
} 

Object.assign(myObject, new MyClass());

myObject.myFunction(); 

Why is this not functioning? I'm getting an error

myObject.myFunction is not a function
.

In my particular case, I am aware that myFunction exists and I just want to transfer it into another instance of a different class. Something like

anotherInstance['myFunction'] = MyClass['myFunction']

...but I understand that this syntax won't do the trick.

I also noticed that this individual's example shows Object.assign copying a function using:

let x = {a: y => y * 2}
let z = Object.assign({}, x)
console.log(z.a(5)); // 10

To clarify:

let calculator = {double: y => y * 2}
let clone = Object.assign({}, calculator)
alert(clone.double(5)); // 10

However, in my original example with a class instance, it doesn't seem to work, presumably due to the mysterious relationship with the prototype.

UPDATE

Currently, I've opted to convert multiple classes into objects to simplify things:

class foo {
  foodle() {
    console.log('1')
  }
}

const bar = {
  fiddle: () => {
    console.log('2');
  }
}

var test = new foo();
var test2 = Object.create(bar);

Object.assign(test, bar);

test.foodle(); // 1
test.fiddle(); // 2

While I prefer using classes for all components, if there's a solution that allows me to switch back to using classes, I'm open to suggestions!

UPDATE 2

Upon further reflection, this approach actually does work:

let myObject = {}

class MyClass {
  myFunction() {
    alert('hello');
  }
} 

var myClassInstance = new MyClass();

myObject['myFunction'] = myClassInstance['myFunction'];

myObject.myFunction(); // hello

Answer №1

Unraveling the mystery of JavaScript prototyping: Class methods reside in the class function's prototype property, from which they are inherited by instances of the class. One technique to transfer a method from one class to an instance of another is by utilizing this pattern:

otherInstance['fiddle'] = Bar.prototype.fiddle

In this scenario, Bar represents the class containing the method fiddle.

An alternative strategy involves accessing class methods directly from an instance by examining its method inheritance:

otherInstance.fiddle = Object.getPrototypeOf(bar).fiddle

Alternatively, the method can simply be inherited in the usual manner:

otherInstance.fiddle = bar.fiddle

Here, bar refers to an instance of Bar, indicating that the first object in its prototype chain is Bar.prototype.

For a non-enumerable addition of methods without affecting inheritance, consider using Object.defineProperty. And if you desire a child class to inherit all properties from a parent class, explore the class extends syntax.

As for Object.assign, it solely transfers enumerable own properties between objects. Class methods, being neither enumerable nor direct properties of instances, are unaffected by this method.

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

Organize array of objects based on the "dataPrin" field

I've been attempting to group this array by the "dataPrin" field for some time now, but without success. It's worth noting that there are two instances of the "dataPrin" field displaying the same date. My goal is to organize this array in a way ...

Using jQuery to replace an HTML element multiple times

Seeking assistance for implementing functionality that replaces a button with an input field, where users can enter information and hit enter. Once the action is completed, the original button should reappear. The current script works effectively but lacks ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

Incorporate a line break into a document using JavaScript

Is there a way to make all the items inside document.get on new lines without using paragraph elements? I have tried br/ and \n, but they do not work as expected. They either cause issues with JavaScript execution or fail to create new lines. <scr ...

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...

Transforming a collection of string arrays into a tree format, as well as reversing the process to convert the tree back into a list of string arrays

I am working with a sorted array containing lists of string arrays: 0:['BS', 'MS','KHB', 'CCBPO'] 1:['BS', 'MS','KHB', 'HBPO'] 2:['BS', 'MS','KHB' ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Running a Node.js worker on an Amazon ECS-hosted server: A step-by-step guide

Our team is currently running a node server on Amazon ECS that receives up to 100 hits per second. Due to the single-threaded nature of JavaScript, we are hesitant to block the event loop. As a solution, we are looking to implement a worker that can peri ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...

Error in HTML: Text variable is not displaying the number value

Currently, I am facing a challenge with my code. I have a variable named "Timer" that I want to increment by one and then display the number. However, I am unable to see the "Test Successful!" message displayed on the screen. Surprisingly, there are no e ...

Passing the value of a radio button to a component in React: a comprehensive guide

I've been struggling to figure out how to pass the value of a selected radio button to another component in React. Currently, I'm exploring the Star Wars API and attempting to create a basic search interface where users can retrieve information a ...

Creating a unique button for STRIPE payments in Laravel 5.1

I have a Stripe payment button in my ecommerce website that looks like this: <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_yNuawoy0jUqj1GC14jwcQR5d" data-amount="{{ $total * 100}}" data-name="dixard" data ...

Error (CODE5022) JavaScript detected in Internet Explorer 10

Here is the code that I wrote: AjxException.reportScriptError = function(ex) { if (AjxException.reportScriptErrors && AjxException.scriptErrorHandler && !(ex instanceof AjxException)) { AjxException.scriptErrorHandler(ex); ...

Using the superagent library to customize request headers in ES6 without relying on Access-Control-Request-Headers

Although I have read through this post, I am still struggling with setting a custom header using ES6 in superagent. Has anyone else encountered this issue? The problem arises when I try to set the header using .set method - only the Access-Control-Request- ...

The javascript code appears to be functioning properly on desktop browsers but is not functioning as expected on Chrome's mobile browser

On my WordPress site, I have created a Java Bootstrap loan calculator that works perfectly on desktop. However, when I use Chrome on mobile, it is not functioning properly. I tried using the wp-coder plugin and also manually added the necessary code. Int ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. How ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...

Learn how to resolve the issue of "Property 'item' does not exist on type 'never'." in Angular using TypeScript with the following code snippet

addToCart (event: any) { if ("cart" in localStorage) { this.cartProducts = JSON.parse(localStorage.getItem("cart")!) console.log(event); let exist = this.cartProducts.find(item => item.item.id == event.item.id); ...

Tips on establishing validators for deeply nested form controls within form groups in Angular 6 reactive forms

In my form array (experiencesArray), I have nested nested nested form controls (companyname), as shown below. this.personalFormGroup = this._formBuilder.group({ professionalInfo: this._formBuilder.group({ totalexpyears: ['', Validators.req ...