Why is it that the context object switches to the global window object when we save a method in a variable and proceed to call it?

Extracted from jqfundamentals, here is an example:

var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function() {
    log( 'Hi, ' + this.firstName );
  }
};

var sayIt = person.greet; // save method into a variable

sayIt(); // displays 'Hi, undefined' -- problem!

To clarify,

When we save the .greet() method in sayIt and then invoke sayIt(), the context changes to the global window object instead of the person object. Since the window object does not contain a firstName property, it returns undefined when accessed.

The issue at hand is

After saving the .greet() method in sayIt and calling sayIt(), why does the context shift to the global window object?

Answer №1

Check out the details in the ecma-262/5.1/#sec-10.4.3

Here's what happens when the execution context of function code within function object F is entered, along with a provided thisArg and argumentsList:

  1. If the function code is strict code, then set the ThisBinding to thisArg.
  2. Otherwise, if thisArg is null or undefined, set the ThisBinding to the global object.

.......

Therefore, in strict mode, this will point to undefined, otherwise it will reference the global object.

Answer №2

When you don't assign any context, the "this" keyword defaults to referring to the global window object. This is because there is no specific context set for it.

If you're interested in learning more about this concept, check out this link:

The usage of the 'new' keyword can be tricky and confusing. It affects how 'this' is interpreted within an object or function. When 'new' is present, 'this' refers to the specific object being created, which makes sense. However, if 'new' is not used, 'this' defaults to the global Window object. This behavior can lead to unintended consequences and polluting the global object. Be cautious when working with 'this' in your code.

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

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Achieving a smooth transition from a blur-out effect to a blur-in effect on a background Div

I created a blur in/out effect for my landing page, but it's not functioning as expected and I'm not sure why. It blurs out correctly, but the issue arises when I want the underlying Div to fade in. Currently, it just appears abruptly after the ...

Extract data from a URL using PHP and JavaScript technologies

Upon receiving a json data from a URL, specifically through celery's flower plugin, the following sample is obtained: { "celery@s1": { "scheduled": [], "stats": { "clock": "2535550", "pid": 26002, "broker": { "tran ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

Real-time JSON Data Retrieval Using Ajax jQuery and Google Sheet API

Seeking a live data search tool that works with JSON spreadsheets Check out this link for more information name = data.feed.entry[i]['gsx$name']['$t']; img = data.feed.entry[i]['gsx$img']['$t']; price ...

Issue: req.flash() not functioning correctly following the execution of req.session.destroy()

In order to log the user out and redirect them to a login page with a message under specific conditions, it is necessary to destroy the user's current session. I usually use the flash feature to display a one-time message in my application, which work ...

Executing an operation in the background while simultaneously collecting additional inputs

I need some help with my data processing script that utilizes selenium. I want to be able to input values and have the script run a function on a website based on those values. Ideally, I would like to queue inputs so I can enter new values while it proces ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas. However, when I attem ...

substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols. (), ||, and ++ are the symbols I'm using. If a text is enclosed in | symbols, it will appear in blue, and so on... Here is the code in action: const text = "|Working on the| i ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

Adjusting the starting point on a 2D canvas with EaselJS translation

When using plain javascript, I was able to change the origin of the canvas to the center by following these steps: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = 1024; canvas.heigh ...

Explore the possibilities of using a unique custom theme with next.js, less, and ant design

Trying to customize the default theme in antdesign has been a challenge for me. I've switched from sass to less, but there seems to be something that just won't work. I've exhaustively searched online for solutions - from official nextjs ex ...

Upgrading from V4 to React-Select V5 causes form submission to return undefined value

Looking to upgrade from react-select v4 to v5. The form/field currently functions with v4 and Uniform, producing an output like this: { "skill": { "value": "skill1", "label": "Skill 1" } } After attempting the upgrade to V5, I'm getting a ...

How to prevent text from overflowing outside the Material UI Container/Box?

One issue I'm facing is with an Alert that displays long strings on my website. Here's the code snippet in question: <Container maxWidth="md"> <Box sx={{ mt: 3, border:1}}> <Box> {hasSubmitted ? ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Updating the subject line in Outlook emails

Can you change the subject of an email that someone receives in Outlook? I believe it might be possible. Perhaps similar to how user agents are used for browsers? I'm fairly new to emails and my online searches have not been helpful despite spending ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...