JavaScript: Incorporating an operator into a specific object (instead of the entire class)

Are you familiar with how to include an operator in an object (rather than the entire class)? When it comes to a method, I know you can achieve that by:

my_object.new_function = function(){return 1};

Then invoking my_object.new_function() will output 1.

However, what I'd like to do is apply the get operator to access my_object.new_function directly instead of using my_object.new_function().

Answer №1

There are a multitude of methods -

let obj = {
  get propX() {
    return 1
  }
}

console.log(obj.propX)
// 1

obj = {
  ...obj,
  get propY() {
    return 2
  }
}

console.log(obj.propX, obj.propY)
// 1 2

Object.assign(obj, { get propZ() { return 3 } })
console.log(obj.propX, obj.propY, obj.propZ)
// 1 2 3

Getters function like regular functions and thus capture their surroundings -

let obj = {
  get propA() { return 1 }
}

let variableB = 2

obj = {
  ...obj,
  get propC() { return variableB } // <- dynamic
}

console.log(obj.propA, obj.propC)
// 1 2

variableB = 999

console.log(obj.propA, obj.propC)
// 1 999

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

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...

Combining two objects in node-red: A step-by-step guide

msg.payload : Object object HAMK307: object a_temperature: 23.1 a_humidity: 46 a_brightness: 3703.05 a_lights: "on" a_presence: "empty" r_temperature: 35.59 r_humidity: 30.46 r_pressure: 994.43 a_time: object ID: "HAMK-307" m ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

Generate real-time dynamic line charts using data pulled directly from a MySQL database

I am in search of guidance on developing a real-time line chart that can dynamically update based on data fetched from MySQL. I need an example or reference on how to achieve this functionality without having to refresh the webpage every time new data is ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...

Making sure the axios API call is completed before rendering the child component with props

Check out the snippet of code I've provided: function StoryCarousel(props) { const [ivrDests, setIVRDests] = useState([]); useEffect(() => { async function getIVRDests() { var data = { "customer-id": ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my d ...

Undo a CSS transition when clicked

There is a div named learn-more which expands to fill the whole page when a CSS class is added like this: .learn-more{ padding:10px; font-size: 20px; text-align: center; margin-top:20px; font-family: klight; -webkit-transition:2s; ...