SlideShare une entreprise Scribd logo
1  sur  22
Javascript
‘this’ keyword
Pham Tung - Aug 2015
What is this?
Definition
this is a special identifier keyword - pointing to
the “owner” of the function being executed.
The value of this is based on the context in
which the function is called at runtime.
Global Context
console.log(this === window); // true
Function Context
function f1(){
return this;
}
f1() === window; // global object
Constructor
function Foo(){
this.value = 1;
console.log(this);
}
var obj = new Foo();
console.log(obj.value); // logs 1
‘this’ in Nested Function
var obj = {};
obj.func1 = function() {
console.log(1, this);
function func2() {
console.log(2, this);
}
func2();
}
obj.func1();
Object {}
Window
In–line event handler
<element onclick="doStuff()">
window
HTML Element
doStuff()
DOM event handler
element.onclick = doStuff;
window
doStuff()
HTML Element
Strict Mode
"use strict";
function test(){
alert(this);
}
test();
window.test();
undefined
[object Window]
(function(){
alert(this);
})();
eval() vs setTimeout()/setInterval()
var obj = {};
obj.testEval = function () {
eval("alert(this)");
};
obj.testSetTimeout = function () {
setTimeout("alert(this)", 100);
};
obj.testEval(); // obj
obj.testSetTimeout(); // window
the setTimeout function
is a method of the
window object.
Any code inside the
anonymous function that
is passed into the
setTimeout call has
window as it’s context
Execution
Context
Syntax of function call Value of this
Global n/a global object (e.g. window)
Function Method call:
myObject.foo();
myObject
Function Baseless function call:
foo();
global object (e.g. window)
(undefined in strict mode)
Function Using call:
foo.call(context, myArg);
context
Function Using apply:
foo.apply(context, [myArgs]);
context
Function Constructor with new:
var new Foo = new Foo();
the new instance
(e.g. newFoo)
Evaluation n/a value of this in parent contexteval()
Controlling the Value of
this
Changing ‘this’ context
var obj = {value: 100};
function add(num1, num2){
alert(this.value + num1 + num2);
}
add.call(obj, 200, 300);
add.apply(obj, [200, 300]);
var objAdd= add.bind(obj);
objAdd(200, 300);
that = this
var boy = {
name: "Bill",
girlFriends: ["Emma", "Mia", "Ava"],
showGirlFriends: function () {
var that = this;
this.girlFriends.forEach (function (item) {
console.log (that.name + " has a girlfriend called " +
item);
});
}
};
boy.showGirlFriends();
Quiz
Quiz 1
function alertThis(){ alert(this); }
(function(){
eval('alertThis()');
})();
Quiz 2
var obj = {};
obj.test = function () {
setTimeout(function () {
alert(this);
}, 100);
};
obj.test();
Quiz 3
<input type="button" id="button1" value="Button 1" onclick="test(this)" />
<input type="button" id="button2" value="Button 2" />
window.test = function(){
alert(this);
}
document.getElementById("button2").onclick = test;
http://jsfiddle.net/yinyang/fju34vkg/
Quiz 4
<input type="button" id="button" value="Click Me" />
function Foo() {
this.value = 100;
this.showValue = function () {
alert(this.value);
}
}
var foo = new Foo();
foo.showValue(); // (1)
document.getElementById("button").onclick = foo.showValue; // (2)
http://jsfiddle.net/yinyang/tLuseowc/
References
https://javascriptweblog.wordpress.com/2010/08/30/understanding-
javascripts-this/
http://code.tutsplus.com/tutorials/fully-understanding-the-codethiscode-
keyword--net-21117
The End!

Contenu connexe

Tendances

AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureManish Jangir
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 

Tendances (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Angular
AngularAngular
Angular
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
React render props
React render propsReact render props
React render props
 
ReactJS
ReactJSReactJS
ReactJS
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 

En vedette

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternNarendra Sisodiya
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu SpringAn Nguyen
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)Trupti Agrawal
 
Prototype-based Programming with JavaScript
Prototype-based Programming with JavaScriptPrototype-based Programming with JavaScript
Prototype-based Programming with JavaScriptlienhard
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxRaja V
 
Trees data structure
Trees data structureTrees data structure
Trees data structureSumit Gupta
 

En vedette (9)

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
Luận văn tìm hiểu Spring
Luận văn tìm hiểu SpringLuận văn tìm hiểu Spring
Luận văn tìm hiểu Spring
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
Prototype-based Programming with JavaScript
Prototype-based Programming with JavaScriptPrototype-based Programming with JavaScript
Prototype-based Programming with JavaScript
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 

Similaire à JS this Keyword Understanding the 'this' Context in JavaScript

Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution ContextJuan Medina
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptLeonardo Borges
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 

Similaire à JS this Keyword Understanding the 'this' Context in JavaScript (20)

Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
this
thisthis
this
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Object oriented JavaScript
Object oriented JavaScriptObject oriented JavaScript
Object oriented JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
4front en
4front en4front en
4front en
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
Function
FunctionFunction
Function
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 

Dernier

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Dernier (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

JS this Keyword Understanding the 'this' Context in JavaScript