Skip to content

Instantly share code, notes, and snippets.

@stantona
Created December 24, 2012 06:25
Show Gist options
  • Select an option

  • Save stantona/4368067 to your computer and use it in GitHub Desktop.

Select an option

Save stantona/4368067 to your computer and use it in GitHub Desktop.
### The current context
The value of `this` in a javascript function call depends on the *execution context* of the function. If we take the above execution of `Simple()` but exclude the new keyword,
`this` would refer to the global object and the `name` property would be added to that object. In a browser the global object is `window`, so in this example, name would be a property of
the `window` object:
``` javascript
Simple();
console.log(window.name);
=> "Adam"
```
However for method functions, that is, executing functions that are referenced by object properties:
``` javascript
simple_obj = {
name: "Adam";
sayHi: function() {
return this.name + " says Hi!";
};
}
simple_obj.sayHi();
=> "Adam says Hi!"
```
the value of `this` is bound to `simple_obj` at invocation. In other words, since `simple_obj` is the receiver of the `sayHi` function call, the *current context*
is now `simple_obj`, not the global object.
Just note that if you have a nested function within a method function (yes you can nest functions in Javascript):
``` javascript
simple_obj = {
name: "Adam";
sayHi: function() {
log = function() {
console.log("sayHi was called by " + this.name);
}
log();
return this.name + "says Hi!";
}
}
```
the value of `this` refers to the global object and is not bound to `simple_obj` like its parent. This is because `log` is not invoked on a *method reciever*.
This doesn't seem very intuitive, but consider the rule is that a function invocate requires a *reciever* for `this` to be bound, no matter
how the function is scoped. This is why you see code like `var that = this`:
``` javascript
simple_obj = {
sayHi: function() {
var that = this;
log = function() {
console.log("sayHi was called by " + that.name)
}
log();
return this.name + " says Hi!";
}
}
```
The `that` local variable is accessed through the closure, and hence the inner function is able to access the context of its parent function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment