Slaying `this` in Javascript
Jim Cummins
Twitter/Github: @jimthedev
Slides: http://tiny.cc/slaying-this
Developer
Commitizen author
Developers
`this`
Stand up!
Air squats
function myFunction() {
console.log('Hello world');
}
myFunction();
Function declaration
Instructions to be executed when the function is called.
Functions in Javascript
Call site
Tells Javascript to actually call the function.
Call stack
(empty)
> myFunction
Ignore
Ignore
Ignore
Execute!
Return
Execute
Execute
Execute
(global)
Let's see a quick example of the keyword `this` in Javascript.
For many developers new to Javascript...
Why does `this`
seem difficult?
Slightly different semantics in other programming languages.
"Today I woke up feeling well rested. This is going to be a great day!"
But...Even context is a hard word to define.
Why does context
seem difficult?
In the above sentence, the context is implicit.
Mark went to the store today. He bought 5 apples.
Determining context in plain English
Mark went to the store today and saw Juan. He bought 5 apples.
Mark went to the store today and he bought 5 apples. While there Mark saw Juan.
In this context, he refers to Mark.
In this context, he refers to ???
In this context, he refers to Mark.
Implicit &
Unambiguous
Explicit &
Unambiguous
Implicit &
Ambiguous
Why does context matter in Javascript?
Context matters so that we can determine what the `this` keyword actually refers to.
In many languages, context is only provided to`this` implicitly.
In Javascript we have the power to set context explicitly using apply(), call(), or bind().
Types of Contexts
Implicit
Explicit
New
Default
Implicit Binding
When `this` gets set because a function is a member of an object.
Explicit Binding
When `this` gets set as a result of using .call(), .apply(), or .bind()
New Binding
When `this` gets set as a result of calling new Foo();
Default Binding
The result of no other binding being set.
Explicit: .apply(), .call()
Explicitly set the context of a given function call.
Overrides any implicit binding that might have been set.
Explicit: .bind()
Bind gives us the benefits of apply() or call() but instead of immediately invoking the function it creates a new function.
Thank you!
Questions? Comments? Concerns?
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
http://ryanmorr.com/understanding-scope-and-context-in-javascript/
https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md
Sources
slaying-this-in-javascript
By jimthedev
slaying-this-in-javascript
- 1,266