Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge.

const example = {
    myFunction(){
        console.log(this);
    },
    myFunction2(){
        function myFunction3(){
            console.log(this)
        }
        return myFunction3()
    } }

When I execute the code

example.myFunction2()

I get the global window object. I'm a bit perplexed by this. My inquiries are:

  1. Can myFunction2() access myFunction3() because of their hierarchy? If so, is there a way to directly access myFunction3() without going through myFunction2()?
  2. Why does this in myFunction3() return the global window instead of referencing myFunction3() itself?

Thank you for your assistance!

Answer №1

1. Trying to access myfunction4 using the method "test.myfunction3.myfunction4()" is not possible.

This is because myfunction4 is not a property of myfunction3, and test.myfunction3 is not an object.

2. Since myfunction4 is a function and not a method, the keyword "this" refers to the Window object within myfunction4.

In methods, "this" refers to the parent object, but in functions, it refers to the global object like Window.

Answer №2

The reason for accessing the global object is related to how you are calling your function, not where the function is located.

When I mention "invocation," I am specifically talking about ==> test.myFunction3()

Object methods can be tricky to understand, but simply having a function inside another doesn't affect its behavior. What counts is how the function is called, like in test.myFunction3()

Answer №3

Is it possible for myfunction3() to directly access myfunction4() without going through its hierarchy? If so, how can I achieve this?

You cannot directly access myfunction4() through myFunction3(), but you can obtain a reference to it and then utilize that reference. In the example below, I also identify a mistake in your implementation of myFunction3()

const func4 = myFunction3();

func4();

Why does this in myfunction4() return the global window object instead of a reference to myfunction4()?

There are two issues at play here. Firstly, 'this' in a function is dynamically bound at runtime.

Secondly, due to a typo in myFunction3(), you are returning the result of calling myFunction4 rather than returning a direct reference to the function itself, which seems to be your intention.

myfunction3(){

    function myfunction4(){
        console.log(this)
    }
    return myfunction4; // Instead of returning the result of calling the function (remove the ())
}

Answer №4

Maybe the solution was to convert it into an object for the function call to work properly, as shown below:

var name = 'global';   // when 'this' scope is global

var test = {
    name: 'local',   // when 'this' scope is local to test
    fun1: function() { //functions defined as object methods
        console.log(this.name);
    },
    fun3: function() {
        function myfunction4(){
            console.log(this.name);
        }
        return myfunction4()
    } 
}

If you wanted to call the functions in a similar way to before, you could do so like this:

test.fun1();     // local

test.fun3();    // global (due to inside of fun4) 

You cannot directly call fun4, but you can retrieve the value by calling fun3.

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

The Owl Carousel npm package is experiencing issues within a ReactJS environment

Currently, I am developing a reactjs application and utilizing the owl carousel npm module to display some data. In my codebase, there is a component dedicated solely to rendering the owl carousel. To achieve this functionality, I have installed the owl c ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

Improving communication between Components in ReactJS

I am attempting to update the state from one component to another component. I wish for the state total on header.jsx to be updated when I click on the add to cart button on product.jsx Below is my code: index.jsx // Code for index.jsx goes here head ...

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

Clear existing markers from the map before inserting new markers

I have a map where initially the markers load coming from the database, Then there is a time-based Ajax request that fetches new records every minute. In my code snippet, I am using setMapOnAll(null) following the guidance from the Google Maps Documentati ...

Converting MiniZinc CSP to JSON using a workaround for iterating through arrays in JavaScript

Utilizing the node.js module "Governify CSP Tools" to tackle a CSP issue has been challenging. Despite following the guidelines on defining an array from the CSP model schema (https://www.npmjs.com/package/governify-csp-tools), I have encountered syntax er ...

I want to create a custom jQuery slider totally from scratch

Greetings everyone, I have been tasked with creating a slider using only HTML / jQuery code. Here is the template: And here is the HTML code for the template above: <div id="viewport-container"> <section id="sliding-container"> & ...

Numerous Customized Google Maps

On my contact page , I have a Google Map V3 that is styled and mostly functional, except for some sprite image display issues. Now, I need to include the same JSON data in two separate maps on my showrooms page . How can I style multiple maps with differen ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

Creating an event listener with a dynamic name

I'm in the process of developing a customizable button bar where I need to attach onclick event listeners to each button dynamically. The functions to be assigned should have names provided by the button's data-function attribute. … <div cl ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

Using importNode in the context of Microsoft Edge involves transferring a

I am facing an issue with a dynamic page that has the ability to change its main div content using a bar button. The pages are mostly static except for one which contains JavaScript (RGraph charts). To make it work, I am currently using the following code ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

Connecting a controller to a directive in AngularJS: A step-by-step guide

Imagine a scenario with the following HTML structure: <div ng-app="testApp"> <div ng-controller="controller1"> {{controller1}} </div> <div ng-controller="controller2"> {{controller2}} </div> ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Modifying a JavaScript code with document.write(variable)

I am working with a Javascript function function setComparison(data) { var w= window.open('', 'comparison', 'width=600, height=400'); w.document.open(); w.document.write(getComparisonContent(data)); w.document ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...