Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object:

var o = {
    prop: 3,
    method: function() {return this.prop}
}

My expectation was that calling

(o.method)()

would result in undefined, but instead it returned 3, indicating that the reference of this is set to o inside the method. Why does this happen? When I evaluate (o.method) separately, it appears as a standalone function, leading me to believe that this would refer to the global object. The distinction becomes apparent in the following comparison:

(o.method)() vs (o.method || true)()

I am aware that o.method() will use o as the context; my question specifically pertains to initially accessing the function like this (o.method) before invoking it.

Answer №1

That's just how the rules of JavaScript operate. Unless you perform some specific actions, this typically refers to the object before the dot when you access the method before calling it. In this scenario, that would be o.

The following statements all have the same effect:

(o.method)();
o.method();
o.method.call(o);
o["method"]();

However, if you assign the method to a different object, it will then refer to that specific object:

var p = {prop: 42, method: o.method};
p.method(); // returns 42

var method = o.method;
var prop = 13;
method(); // returns 13

Note: As JavaScript evolved beyond its original purpose, it became clear that the behavior of this may not be the most intuitive. In ES6, with the introduction of "Arrow Functions" (also known as Lambda Functions), this will no longer be rebound.

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

JavaScript Routing with Multiple Files

I tried to access api.js from Routes.js, but I encountered an issue stating that the function my_function_in_api is not defined. Here is my code, could you please help me identify where the problem lies: Routes.js var val = require('file name') ...

Confirm that one input falls within a specified range of two inputs

I am trying to implement javascript validation for a form with two inputs. Specifically, I want to achieve the following: If a text input is entered and the dropdown remains unselected, the validation should trigger for the text input and the form should ...

Typehead.js on Twitter is displaying the full query instead of just the value

The Problem This is the issue I am facing with my code. My goal is to retrieve only the value, but instead of that, the entire query value is being returned. var engine; engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue&apo ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...

Using AngularJS to dynamically swap out {{post.title}} with a different HTML file

I want to update the value of {{post.title}} within my HTML to redirect to another HTML file. <div ng-repeat="post in posts"> <h2> {{post.title}} <a ng-click="editPost(post._id)" class="pull-r ...

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

display saved data from ajax request

I've been working on saving data and files using ajax. Following a tutorial (link), I managed to successfully save the data in the database and the image files in the designated folder. However, I'm facing an issue where the success or error mess ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

Sharing specific props with deeply nested components in React

I am experimenting with configuring props for children components. In this example, I am testing a function to target any child, whether nested or not, with the prop swipeMe. It works perfectly when the render function contains only a single child, like ...

Hovering triggers the appearance of Particle JS

I am attempting to add particle js as the background for my website. I have tried implementing this code snippet: https://codepen.io/nikspatel/pen/aJGqpv My CSS includes: position: fixed; z-index: -10; in order to keep the particles fixed on the screen e ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Is there a specific HTML tag available to instruct the browser to cache my HTML and/or CSS files for future use?

Up to this point, my research has indicated that enabling JavaScript and CSS browser caching typically requires server side settings such as .htaccess. Is there any HTML tag or configuration within the HTML page or JavaScript that can instruct the browse ...

Changing text array to field identifiers with JavaScript

Is there an elegant way in ECMAScript 6 to transform a string array generated from a map function into field names within a dynamically created object? For instance, if I receive the following output from my map function: ["checkbox1Value", "checkbox4Val ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

JQuery form serialize not triggering in Internet Explorer

I've encountered an issue with a form inside a jQuery dialog that is not submitting properly in Internet Explorer. The form functions correctly in Chrome and Firefox, sending data to my MVC controller without any issues. However, when using IE, it on ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...

Continuous Load More: Loads content infinitely until a page is fully loaded

I am currently experimenting with implementing infinite ajax scroll within a Bootstrap modal. Below is the initial appearance of the modal, before any data is loaded: <div class="modal fade" id="modal" tabindex="-1"> <div class="modal-dialog" ...

Issue with Highcharts: Border of stacking bar chart not visible on the right side

When creating a stacking bar chart, I noticed that the rightmost 'box' does not have a border drawn on the right side. Is there a setting or option in Highcharts that can be used to ensure the white border line is drawn around the 75% box in the ...