At what moment does the object returned from a get method come into existence?

Exploring the code below:

var obj={
       prop1:7,
       get prop2 (){
          console.log('I ran');
          return {a:1,b:2}     
       }
}

At what point is the object {a:1,b:2} created?

Is it created when the code above is executed, or only when we explicitly call obj.prop2? This question arises because accessing obj.prop2.a returns 1 without calling obj.prop2, which is puzzling. How does it know the value of obj.prop2.a without running obj.prop2?

Another intriguing observation is that in the console, when typing obj.prop2., auto completion suggests options including a and b. How is this possible if we haven't called obj.prop2?

Answer №1

At what point is the object {a:1,b:2} created? Is it when the code is initially run or only when obj.prop2 is explicitly accessed?

The object {a:1, b:2} is created when we access obj.prop2, as this triggers the getter function. This results in a new object being returned every time the property is accessed:

var obj={
       prop1:7,
       get prop2 (){
          console.log('I ran');
          return {a:1,b:2}     
       }
};
document.body.innerHTML = obj.prop2 == obj.prop2; // false

Consider the following analogy:

// One:
var obj = {
    f: function() {
        return {a:1, b:2};
    }
};
// Two:
obj.f();

In this scenario, the object {a:1, b:2} is created at "Two:", not at "One:". Each time f() is called, a new object is created.

When we type obj.prop2 in the console, it auto-suggests properties like a and b along with others. How does this work?

The console reads the property to determine its value and provide auto-suggestions, similar to how it handles other properties. For example, in Chrome, you may see "I ran" displayed when typing "." after obj.prop2.

You can test this in your own console environment:

var obj = {
    x: 1,
    get prop() {
        var o = {};
        ++this.x;
        o["___" + this.x] = "foo";
        return o;
    }
};

Then type

obj.prop.

...and observe the property named ___1. If you delete the ".", then retype it, you will now see the property ___2. The console reads the property each time, invoking the getter function.

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

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...

Accessing the page directly in a Nuxt SPA is not permitted

I'm currently working with Nuxt version 2.3.4. In my project, I am utilizing vue-apollo to fetch data for a file named pages/_.vue, which dynamically manages content. As indicated on this documentation page, this is the recommended approach for handli ...

Unable to retrieve information from JSON using jQuery's AJAX method

My journey with learning JSON using jQuery has hit a bump in the road. Despite spending two days and going through various tutorials on YouTube and blogs, I'm facing a challenge. The JSON structure presented in the tutorials differs from the one I hav ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Guide on transferring data from a JSON file to a JavaScript array

Currently, I am manually declaring the countries list for my typeahead search. To streamline this process, I want to retrieve the data from an external JSON file named countries.json. Here is a snippet of what the JSON file contains: [ { "id": ...

What is the layout of JqueryMobile web pages like?

When I need to pull pages, I use Asp.net MVC. The format of my pages is as follows: { Layout = ""; } <div data-role="page"> .... <script type="text/javascript"> $(document).one("pageinit", function () { . ...

Where can rootScope values typically be found - in a cookie or local storage?

What is the storage location of rootScope values - cookie or local storage? I am uncertain about how rootScope works in angularjs. I am passing a value between two controllers, so I am using $rootScope. I would like to understand how $rootScope ...

Can you please provide a method for determining which characters are adjacent to each other

I am in the process of developing a markdown editor and I require a check to identify if adjacent characters are specific characters, removing them if they match or adding them otherwise. For example, if the selected text is surrounded by two asterisks li ...

Steps for revealing a section of a webpage by completing an HTML form

Looking for a way to validate and store data from an HTML form in order to reveal a specific section of my webpage. Here's the scenario: I run an online shop and want to capture leads. On my landing page, I want to only show the purchase button and p ...

Use jQuery to collapse all of the child elements that are currently expanded under a specific parent element

In my list order, I have multiple levels nested within each other: <ul> <li>level 1 a <ul> <li>level 2 a <ul> <li>level 3 a</li> < ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

Angular factory variable scoping

I am encountering an issue with altering the folders variable (an array) within the return statement of my Angular factory. It seems to work for the create action, but I am having trouble with the scope of the variable in the factory. This code works: fo ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

We encountered an issue while trying to utilize the react-awesome-query-builder npm package within our next.js project, specifically struggling to include multiple

I am attempting to create a query builder similar to the demo using the provided documentation ... when I add more fields in the config, new options appear in the dropdown ... I tried using multiple Builder components to create more fields and even experim ...

The focus is being lost on the ng-model when used within an ng-repeat

Within my JavaScript code, I am initiating a new question object like this: $scope.newQuestion = { answers: [] }; This is how it reflects in the HTML: <div class="row" ng-repeat="answer in newQuestion.answers"> <div class="input-field col m ...

What is the method for locating line spacing within HTML code?

After posting a previous question, I am still on the quest to determine the exact position of each line of text within an element. While I was successful in identifying the css lineHeight attribute (as mentioned in the previous response), I encountered an ...

Create a JavaScript code snippet that replaces the innerHTML of the function document.getElementById with

In my limited knowledge of JavaScript, I have come across an issue with the following code: function example() { document.getElementById("example").innerHTML = "<script>document.write(example)</script>"; } Unfortunately, this code doesn&ap ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Exploring navigation within a React application

After attempting to develop a react native application and finding it too difficult for my needs, I decided to switch to React. As a beginner in web programming, I recall learning about the concept of 'navigation' in react native, including vario ...

Adjust the camera in threejs to be positioned inside a different object

My goal is to adjust the camera controlled by trackballControl to match the position of an object. Currently, it's functioning correctly but as demonstrated in this example, each time the camera changes its position, the z value also changes, which i ...