Is it possible to manipulate the attribute of an object using Object.defineProperty when a value is passed as a function parameter?

As I delve into understanding reactivity in Vue, the concept of how reactivity is achieved when passing a value as a function parameter perplexes me.

//here is the actual code snippet

var obj = {a: 'aa'}
function reactive(obj, key, value) {
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get() {
            return value
        },
        set(val) {
            value = val
        }
    })
}
function observe(obj) {
    Object.keys(obj).map((key, index) => {
        reactive(obj, key, obj[key])
    })
}
observe(obj)
obj.a //'aa'
obj.a ='bb' //'bb'

//here is the error-inducing code snippet

var obj = {a: 'aa'}
function reactive(obj, key) {
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get() {
            return obj[key]
        },
        set(val) {
            obj[key] = val
        }
    })
}
function observe(obj) {
    Object.keys(obj).map((key, index) => {
        reactive(obj, key)
    })
}

observe(obj)
obj.a //VM1649:6 Uncaught RangeError: Maximum call stack size exceeded

When attempting to set the value using 'obj[key]', it results in a RangeError

//this is an illustrative example

var obj = {a: 'aa'}
function reactive(obj, key, value) {
   value = 'bb'
}
function observe(obj) {
    Object.keys(obj).map((key, index) => {
        reactive(obj, key, obj[key])
    })
}
observe(obj)
obj.a //'aa'

Nevertheless, the example emphasized that modifying the object's value through assignment is not possible within this context

Answer №1

When attempting to access obj[key] in the error code, it causes the getter of obj[key] to be invoked repeatedly, resulting in the display of Maximum call stack size exceeded. To avoid this issue, it is recommended to provide the value as the third argument in the function reactive.

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

Recently updated to the latest versions of Angular, AngularCLI, and Rxjs (version 6), however encountering an error stating "Property 'take' does not exist on type 'Observable'"

Recently, I made the decision to update my Angular5 project to Angular6 and upgraded all dependencies along with it (such as rxjs now at version 6 and angular-cli). However, I have encountered a problem that is proving difficult to resolve: ERROR in src/ ...

Error: Express JS custom module cannot be located in the root directory's modules folder

The file structure of my express js app resembles this I'm attempting to load a modules folder from the root directory. routes/users.js var express = require('express'); var router = express.Router(); var md=require('./modules') ...

Exploring the World of Popper.js Modifiers

Within our React and Typescript application, we integrate the react-datepicker library, which utilizes popper.js. Attempting to configure PopperModifiers according to the example provided here: . Despite replicating the exact setup from the example, a typ ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

How to iterate through a JavaScript array in reverse order using a for loop and the array's length property

When looking to iterate through an array with the values [8,7,6,5,4], some may wonder why a for loop using the length of 5 continues to function even though there is no element at index 5 in the array. for(let i=array.length;i>=0;i++){ //do somethin ...

How can we export data to excel using react-export-excel while ensuring certain columns are hidden?

Greetings! I believe the title gives you a clear idea of my dilemma. When exporting data, there are no errors - my goal is to hide the Excel column when the checkbox is unchecked or false, and display it when the checkbox is checked or true during export. ...

Tips for incorporating a set offset while utilizing the scrollTop() function

I have successfully implemented a code that sets a position:fixed to a div when it scrolls past the top of the screen. The code I used is as follows: var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.o ...

The Card Component from Core UI fails to appear in the Print Preview feature

I'm currently experimenting with the Card Component from the Core UI framework. However, I'm facing an issue where the color of the Card component and its associated icon do not appear in the Preview when trying to print the page. I attempted to ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Having trouble with a JQuery ajax post to a PHP server - receiving the error message "SyntaxError: Unexpected token < in JSON at position 0"

I am attempting to transmit json data to a server and retrieve a json response. My code is displayed below: JS: function login() { console.log("clicked"); //gather form values into variables var email = $("#email").val(); var password = $("#password"). ...

Unleashing the full potential of ajax through endless scrolling performance

Recently, I implemented an infinite scroll feature on my website's index page by making ajax requests to retrieve a JSON containing 40 objects. Then, I add them using a JavaScript loop. However, I've noticed that it slows down the site at times. ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

Modifying the color scheme of Google Maps API V2

I am trying to customize the color of the direction line in Google Maps API. I have checked the documentation, but couldn't find any information on changing the color. Below is my code: function direction() { var txtAddress = document.getElement ...

Switch body class when the navbar's collapse show class is toggled

There are numerous methods to accomplish this task, but I am seeking the most optimal and efficient approach. My goal is to toggle a custom body class when the .navbar-toggle triggers the .show class on the .navbar-collapse element. I'm hesitant abo ...

Issue with Codeigniter's AJAX functionality causing div reloading to not function as intended

I am currently facing an issue where I can display text directly from the database on a webpage. However, when I edit the text in the database, I want it to automatically reload and show the updated text without having to refresh the entire page. Unfortun ...

Different ways to shuffle the arrangement of divs

Forgive me if this seems like a simple query, but I am struggling with it. Essentially, what I want to achieve is to randomize the positioning of the items, where item 1 can adopt the style of item 3 (or 2 or 4), item 2 can take on the style of 1, 3, or 4, ...

Managing the position of the caret within a content-editable div

I need help with editing a contenteditable div in HTML <div contenteditable="true" id="TextOnlyPage"></div> Here is my jQuery code: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm"); $('#TextOnlyPage').keyup(function( ...

Travis-CI build encountering errors, however, local tests and builds run smoothly

I'm encountering difficulties getting my unit test to pass with Travis. When running the tests locally, I don't see any errors (unit/e2e)... If you'd like to see the log file, it can be found here in the Travis build log There are numerous ...