SlideShare a Scribd company logo
this in JavaScript
How it really works
@marthakelly
"this" in JavaScript
JavaScript is weird*
“The best thing about JavaScript is its implementation of functions. It
got almost everything right. But, as you should expect with
JavaScript, it didn’t get everything right.”
- Douglas Crockford, JavaScript The Good Parts
* and WONDERFUL
Functions are first class objects
// Stored in variables
var kitten = function() {
console.log('mew!');
};
// Stored in objects
var kindle = {
“kitten” : “Eula”,
“meow” : function() {
console.log(“meow!”);
}
};
// Stored in arrays
var kindleMeow = [kindle.meow];
// Passed as arguments
$(“#kitten”).on(“click”, function(){
console.log(“meow!”);
};
// Returned as values
var kitten = function() {
var secret = “this
};
Execution Contexts
✤ Global Context
✤ Function Context
✤ Eval Context*
*handslap!!
Functions, interpreted
✤ “Activation” Object is created
✤ “Arguments” Object is created
✤ Scope Chain is assigned*
✤ Variable instantiation happens*
✤ Value for “this” is assigned*
* for the sake of time, we’ll focus on these
Scoping (is hard)
✤ Scope is defined inside the *function* context
✤ Scope is not block level, it is lexical!
+------------------------------+
| global variable obj |
+------------------------------+
^
|
+-----------------------------+
| variable obj for outer call |
+-----------------------------+
^
|
+-----------------------------+
| variable obj for inner call |
+-----------------------------+
Variable Instantiation
✤ Activation Objects stores names for:
✤ parameters
✤ local variables
✤ local functions
✤ Values are UNDEFINED
✤ Values are truly assigned during execution
// this function is written:
var kitten = function() {
console.log(meow);
var meow = “meow!”;
};
// this function is interpreted:
var kitten = function() {
var meow = undefined;
console.log(meow);
meow = “meow!”;
};
kitten();
// undefined
/* Hoisting happens because of
Variable Instantiation! */
Hoisting!
this depends on invocation
✤ As an Object’s Method
✤ this is the parent object
✤ As a Constructor
✤ this is the created object
✤ As a Function Literal
✤ this is the global object
✤ Call/Apply
✤ this is explicitly defined
(based on the argument you
supply to the method)
this is getting weird.
✤ this holds a reference to the object the function is applied to
✤ this does not necessarily mean the object where it is stored
Context is important
var kitkat = {
name : “Kitkat”,
sayName : function() {
return this.name;
}
};
var eula = {
name : “Eula”,
sayName : kitkat.sayName
};
eula.sayName();
// Eula
/*
scope is defined in
the context it
executes
*/
self = this
$('#kitten').click(function(){
// this is a reference to the element clicked on
var self = this;
$('.kittens').each(function(){
// this is a reference to the current element in the loop
// self is still a reference to the element clicked on
});
});
"this" in JavaScript
Closures
✤ A Closure is created when a function returns (or, “closes over”) the
variables it had access to when it was created
✤ It returns that scope property (aka, the chain of variable objects)
Thanks!
✤ Follow me on Twitter!
✤ @marthakelly

More Related Content

PDF
Let's Redux!
PDF
React & Redux
PDF
Avoiding callback hell with promises
PDF
Introduction to Redux
PDF
Introduction to React & Redux
PDF
Angular Performance: Then, Now and the Future. Todd Motto
PDF
The basics of Ember Objects
PDF
Angular redux
Let's Redux!
React & Redux
Avoiding callback hell with promises
Introduction to Redux
Introduction to React & Redux
Angular Performance: Then, Now and the Future. Todd Motto
The basics of Ember Objects
Angular redux

What's hot (20)

PDF
React.js or why DOM finally makes sense
PDF
Let's discover React and Redux with TypeScript
PDF
JavaScript promise
PDF
React JS and why it's awesome
PDF
React + Redux. Best practices
PDF
State Models for React with Redux
PPTX
Amitesh Madhur - Web workers, HTML 5
PDF
JavaScript Promises
PPTX
REACT.JS : Rethinking UI Development Using JavaScript
PDF
Reactive.architecture.with.Angular
PPTX
React + Redux + TypeScript === ♥
PDF
Swift ui userinput
PDF
Creating a WYSIWYG Editor with React
PDF
React, Redux, ES2015 by Max Petruck
PDF
Promise pattern
PPTX
Avoiding callback hell in Node js using promises
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
PDF
React Lifecycle and Reconciliation
PPTX
React with Redux
React.js or why DOM finally makes sense
Let's discover React and Redux with TypeScript
JavaScript promise
React JS and why it's awesome
React + Redux. Best practices
State Models for React with Redux
Amitesh Madhur - Web workers, HTML 5
JavaScript Promises
REACT.JS : Rethinking UI Development Using JavaScript
Reactive.architecture.with.Angular
React + Redux + TypeScript === ♥
Swift ui userinput
Creating a WYSIWYG Editor with React
React, Redux, ES2015 by Max Petruck
Promise pattern
Avoiding callback hell in Node js using promises
Workshop 20: ReactJS Part II Flux Pattern & Redux
React Lifecycle and Reconciliation
React with Redux
Ad

Similar to "this" in JavaScript (20)

PDF
The mighty js_function
PDF
JavaScript Functions
PPTX
Object oriented java script
PDF
JavaScript Execution Context
PDF
Rediscovering JavaScript: The Language Behind The Libraries
PPTX
Javascript talk
PDF
Js interpreter interpreted
PDF
Pragmatic JavaScript
PPTX
PDF
java script functions, classes
PPT
Basic Javascript
PPT
Javascript quiz. Questions to ask when recruiting developers.
PDF
Js in-ten-minutes
PPT
Expert JavaScript tricks of the masters
PPT
Web development basics (Part-4)
PPTX
Awesomeness of JavaScript…almost
PPT
25-functions.ppt
PPT
JavaScript Functions
PDF
Javascript development done right
PDF
Javascript under the hood 1
The mighty js_function
JavaScript Functions
Object oriented java script
JavaScript Execution Context
Rediscovering JavaScript: The Language Behind The Libraries
Javascript talk
Js interpreter interpreted
Pragmatic JavaScript
java script functions, classes
Basic Javascript
Javascript quiz. Questions to ask when recruiting developers.
Js in-ten-minutes
Expert JavaScript tricks of the masters
Web development basics (Part-4)
Awesomeness of JavaScript…almost
25-functions.ppt
JavaScript Functions
Javascript development done right
Javascript under the hood 1
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
A Presentation on Artificial Intelligence
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Modernizing your data center with Dell and AMD
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
KodekX | Application Modernization Development
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
MYSQL Presentation for SQL database connectivity
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Weekly Chronicles - August'25 Week I
A Presentation on Artificial Intelligence
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Advanced methodologies resolving dimensionality complications for autism neur...
Dropbox Q2 2025 Financial Results & Investor Presentation
20250228 LYD VKU AI Blended-Learning.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Modernizing your data center with Dell and AMD
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KodekX | Application Modernization Development
Chapter 3 Spatial Domain Image Processing.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf

"this" in JavaScript

  • 1. this in JavaScript How it really works @marthakelly
  • 3. JavaScript is weird* “The best thing about JavaScript is its implementation of functions. It got almost everything right. But, as you should expect with JavaScript, it didn’t get everything right.” - Douglas Crockford, JavaScript The Good Parts * and WONDERFUL
  • 4. Functions are first class objects // Stored in variables var kitten = function() { console.log('mew!'); }; // Stored in objects var kindle = { “kitten” : “Eula”, “meow” : function() { console.log(“meow!”); } }; // Stored in arrays var kindleMeow = [kindle.meow]; // Passed as arguments $(“#kitten”).on(“click”, function(){ console.log(“meow!”); }; // Returned as values var kitten = function() { var secret = “this };
  • 5. Execution Contexts ✤ Global Context ✤ Function Context ✤ Eval Context* *handslap!!
  • 6. Functions, interpreted ✤ “Activation” Object is created ✤ “Arguments” Object is created ✤ Scope Chain is assigned* ✤ Variable instantiation happens* ✤ Value for “this” is assigned* * for the sake of time, we’ll focus on these
  • 7. Scoping (is hard) ✤ Scope is defined inside the *function* context ✤ Scope is not block level, it is lexical! +------------------------------+ | global variable obj | +------------------------------+ ^ | +-----------------------------+ | variable obj for outer call | +-----------------------------+ ^ | +-----------------------------+ | variable obj for inner call | +-----------------------------+
  • 8. Variable Instantiation ✤ Activation Objects stores names for: ✤ parameters ✤ local variables ✤ local functions ✤ Values are UNDEFINED ✤ Values are truly assigned during execution
  • 9. // this function is written: var kitten = function() { console.log(meow); var meow = “meow!”; }; // this function is interpreted: var kitten = function() { var meow = undefined; console.log(meow); meow = “meow!”; }; kitten(); // undefined /* Hoisting happens because of Variable Instantiation! */ Hoisting!
  • 10. this depends on invocation ✤ As an Object’s Method ✤ this is the parent object ✤ As a Constructor ✤ this is the created object ✤ As a Function Literal ✤ this is the global object ✤ Call/Apply ✤ this is explicitly defined (based on the argument you supply to the method)
  • 11. this is getting weird. ✤ this holds a reference to the object the function is applied to ✤ this does not necessarily mean the object where it is stored
  • 12. Context is important var kitkat = { name : “Kitkat”, sayName : function() { return this.name; } }; var eula = { name : “Eula”, sayName : kitkat.sayName }; eula.sayName(); // Eula /* scope is defined in the context it executes */
  • 13. self = this $('#kitten').click(function(){ // this is a reference to the element clicked on var self = this; $('.kittens').each(function(){ // this is a reference to the current element in the loop // self is still a reference to the element clicked on }); });
  • 15. Closures ✤ A Closure is created when a function returns (or, “closes over”) the variables it had access to when it was created ✤ It returns that scope property (aka, the chain of variable objects)
  • 16. Thanks! ✤ Follow me on Twitter! ✤ @marthakelly