What is the extent of an object within a JavaScript Array?

Exploring scopes in JavaScript has led me to an interesting discovery when calling functions from an array. In the example below, I experiment with three different scopes: one bound to an Object named foobar, one bound to window, and a third one which points back to the function itself. I'm intrigued by why the function is scoped to itself rather than the global window object. Could this be due to Array access being a function call itself, causing the stored function to exist in a local scope?

var foobar = {
  doWork: function() {
      console.log('doing some work...');
      console.log(this);
  }
}

foobar.doWork(); // `this` will refer to foobar

var doWorkClone = foobar.doWork;
doWorkClone(); // `this` will refer to window

var workClones = [];
workClones.push(foobar.doWork);
workClones[0](); // `this` will refer to the doWork function itself

Answer №1

Both functions behave in the same manner. When using a.b(), the function a.b is invoked with the context of a.

foo.bar();  // function is `foo.bar`, context is `foo`
barClones[1]();  // function is `barClones[1]`, context is `barClones`

The notation of . and [] are essentially equivalent. The choice between them is inconsequential, regardless of whether it involves an array or not.

Answer №2

Understanding this concept requires a deep look into how JavaScript functions operate internally.

When you call f(args), JavaScript actually executes f.call(this, args). Therefore, the keyword this always points to the context from which the function is called.

In your specific scenario:

foobar.doWork()   --> foobar
doWorkClone()     --> window or wrapping expression
workClones[0]()   --> "0" exists in workClones, so it refers to workClones

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

Using JSTL with jQuery or JavaScript

I am trying to send array elements from my Java code to a JSP page. The goal is for the array elements to be displayed on the page when a button is clicked. I have attempted to use the JSTL forEach tag within JavaScript or jQuery, but unfortunately, it do ...

Refreshing Bootstrap table data after an AJAX post request

I have implemented a bootstrap table to display rows from a database in MVC ASP.NET. The data is stored in a ViewBag and then returned with the ViewBag included as data to be displayed. Here is an example of how it looks: <div class="row rpad"> ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...

Alter appearance using various classes

I am seeking assistance in changing the font of text using classes. I have multiple texts with different classes and I want to be able to edit all the texts without adding another dropdown menu. I believe that the change needs to occur in a script. Pleas ...

What is the best way to organize columns on the front end?

A table needs to be displayed on the front end with the following code snippet: <logic:present name="searchStudent"> <table class=" tblSearchResult" border="1" cellspacing="0" cellpadding="0"&g ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

How can a JavaScript array be transmitted as a JSON value?

Is there a method to pass a JavaScript array as a JSON variable in my AJAX query? ...

Leveraging the (click) event within an HTML template to manage a [hidden] element located in a different template using Angular 2

Within my project, I have two TypeScript files, each containing HTML templates inside the @Component. In one of the templates, there are info cards that can be collapsed or expanded using [hidden]="collapsed". The following function is present in both file ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

Leveraging API JSON information in conditional return statements with React

Working on a small Express/React app (not for production), I am validating a hashed pin in express and returning either message: false if validation fails or message: <cardnumber> if validation is successful. Currently, in my react frontend, I am try ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

JQuery script fails to load in the head section while dynamically generating an HTML page with JavaScript

Using JavaScript, I have created a new window dynamically and added some HTML code to it. However, when I try to insert a script link into the HTML head, it fails to load when the window is open. <script type="text/javascript"> function newWindo ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

Ensure that the second y-axis in charts.js consistently shows the 100% tick

I have implemented a scatter chart using recharts and it currently looks like this: The right-y-axis in my chart represents the percentage and is showing the correct values as desired. However, I am looking to make a modification so that the 100% mark is ...

CSS - Absolute positioning appears to be slightly choppy in Microsoft Edge

I have successfully implemented a slip scrolling function to reveal/hide a fixed logo on scroll, but I am facing some issues with Microsoft Edge browser. While testing in various browsers, everything works smoothly except for Microsoft Edge. In this brows ...

Display the outcomes of two MongoDB queries simultaneously on a single page

As I dive into the world of MongoDB and Node.js/Express, I find myself struggling to fully grasp some of the concepts. Forgive my inexperience, but I haven't been able to locate a clear answer for what I'm trying to achieve. My goal is straight ...