What causes the anonymous function to drop the object scope?

Is it important for the anonymous function/closure to retain the scope of the object where it originated?

var person = {
name: "John",
func: function() {
    var self = this;
    console.log("outer function: this.name = " + this.name);
    console.log("outer function: self.name = " + self.name);
    (function() {
        console.log("inner function: this.name = " + this.name);
        console.log("inner function: self.name = " + self.name);
    }());
}
};
person.func();

Both examples yield the same result.

var person = {
    name: "John",
    func: function() {
        var self = this;
        console.log("outer function: this.name = " + this.name);
        console.log("outer function: self.name = " + self.name);
        return function() {
            console.log("inner function: this.name = " + this.name);
            console.log("inner function: self.name = " + self.name);
        };
    }
};
person.func()();

// output

outer function: this.name = John
outer function: self.name = John
inner function: this.name = undefined
inner function: self.name = John

Answer №1

This is a fundamental principle of JavaScript (specifically ECMAScript5). Anonymous functions, especially within a closure, do not preserve the context.

You have the option to do something like the following:

(function() {
    console.log("inner function:  this.foo = " + this.foo);
    console.log("inner function:  self.foo = " + self.foo);
}).call(this);

This is because you are explicitly calling the function. If you were passing in a callback, you might consider using Function.prototype.bind instead.

In the case of using ECMAScript6, arrow functions can be utilized to preserve the context of an anonymous callback:

(() => {
  // `this` maintains the context of its parent scope
});

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

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

Effortlessly find data in an HTML table and showcase the results instantly without

I am looking for a way to implement search functionality in my table without refreshing the page. The fields above the table are used for searching and I want the results to be displayed within the same table. Here is an example of the code: <?php $for ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

Displaying a component after retrieving a value from AsyncStorage in a React Native application

I have developed a React Component that saves user settings in the AsyncStorage and retrieves them upon loading. The functionality of storing and retrieving data is working fine, but I am facing an issue where the component renders before the values are ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

Button fails to display as intended despite meeting conditions

I'm currently using a formData object with useState(). Whenever a field is updated in the form, I update formData like this: setFormData({...formData, [field.id]: field.value}) My goal is to have the button at the end of the form change once all req ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

React: Incorporating .map for nested arrays. Ensure each child component within the list is assigned a distinct "key" property

I have an array called navMenuItems that contains data for building a navigation menu with links and link names. Each item in the array may also contain child links, similar to the mobile menu on https://www.w3schools.com/. However, I'm encountering a ...

Escaping quotes in JavaScripts is an important skill to

I have a table called posts. When I add a title enclosed in quotes ("This the new") to the posts table and then try to delete the post using an onclick javascript function, I encounter the following issue: echo "<td><a class='btn btn-danger& ...

Styling nested divs in CSS

I am experiencing an issue where the child divs within parent divs are overflowing outside of the parent divs. To get a better understanding of the problem, please try running the code below in a browser: My goal is to align the innermost divs horizontall ...

Issue with ng-click not triggering the $mdDialog callback

Utilizing Angular Material, I have functionality in TasksCtrl that triggers a $mdDialog - utilizing the locals property to pass an object that will be changed in DialogCtrl before being returned to the view. Nevertheless, the .then() callbacks do not trig ...

Arranged Items according to the value of nested objects

Sorting an object based on the number of votes it has and then mapping over the sorted object can be a bit tricky, especially when trying to retain the original keys. const data = { "comment-1508872637211" : { "description" : "Blah", "votes" : 1 ...

The utilization of 'ref' with React Styled Components is proving to be ineffective

Using refs in Styled Components has been tricky for me. When I attempt to access them in my class methods as shown below, I encounter the error message: Edit.js:42 Uncaught TypeError: this.....contains is not a function constructor(props) { .... ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Having difficulties retrieving the value of the div in the voting system

Whenever the element with the id #upvote is clicked, the value of the element with the id #vote increases by 1. On the other hand, when the element with the id #downvote is clicked, the value decreases by 1. However, there seems to be an issue where if the ...