# Scope of "this" in anonymous functions

**URL:** https://forum.kirupa.com/t/scope-of-this-in-anonymous-functions/294950
**Category:** Uncategorized
**Created:** [August 22, 2009, 11:36pm UTC](https://forum.kirupa.com/t/scope-of-this-in-anonymous-functions/294950 "2009-08-22T23:36:52Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![NeoDreamer](https://avatars.discourse-cdn.com/v4/letter/n/ccd318/32.png) [@NeoDreamer](https://forum.kirupa.com/u/NeoDreamer)
#### Post date: [August 22, 2009, 11:36pm UTC](https://forum.kirupa.com/t/scope-of-this-in-anonymous-functions/294950/1 "2009-08-22T23:36:52Z")

</div>

```php

// using Prototype's Classes
MyClass = Class.create({
   initialize: function() {
      this.myField = null;
      Event.observe(window, 'load', function() {
         this.myField = new Field();
      });
   },
   myMethod: function() {
      alert(this.myField);
   }
});

```

_Field_’s constructor uses Scriptaculous’s sliders, which require an element to be already loaded. That’s why I’m only setting _this.myField_ when the window has loaded. I see that my sliders get initialized properly, but _this.myField_ is still null when I call _myMethod()_. I suspect this has something to do with the scope of _this_ in my anonymous function. How do I fix this to do what I intended?
