SlideShare a Scribd company logo
4
Most read
5
Most read
6
Most read
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!

More Related Content

PPTX
Js: master prototypes
PDF
ZIO-Direct - Functional Scala 2022
PDF
Implicit parameters, when to use them (or not)!
PDF
JavaScript Inheritance
PDF
JavaScript - Chapter 10 - Strings and Arrays
PDF
Callback Function
PPTX
Inheritance in c++theory
PPTX
Php.ppt
Js: master prototypes
ZIO-Direct - Functional Scala 2022
Implicit parameters, when to use them (or not)!
JavaScript Inheritance
JavaScript - Chapter 10 - Strings and Arrays
Callback Function
Inheritance in c++theory
Php.ppt

What's hot (20)

PDF
Effective CMake
PPTX
Constructor in java
PDF
Introduction to Java 11
PPTX
JS Event Loop
PDF
L18 Object Relational Mapping
PPT
C++ oop
PPTX
Introduction to Spring Framework
ODP
Introduction to Java 8
PDF
Asynchronous JavaScript Programming
PPTX
Introduction to java 8 stream api
PPT
Inheritance C#
PPT
Major Java 8 features
KEY
Object Calisthenics Applied to PHP
PDF
Java IO
PPTX
Clean code
PPTX
Clean code slide
PPT
Working with color and font
PDF
Sql Injection Myths and Fallacies
PDF
Functional and Algebraic Domain Modeling
PDF
Troubleshooting SQL Server: Un enfoque práctico
Effective CMake
Constructor in java
Introduction to Java 11
JS Event Loop
L18 Object Relational Mapping
C++ oop
Introduction to Spring Framework
Introduction to Java 8
Asynchronous JavaScript Programming
Introduction to java 8 stream api
Inheritance C#
Major Java 8 features
Object Calisthenics Applied to PHP
Java IO
Clean code
Clean code slide
Working with color and font
Sql Injection Myths and Fallacies
Functional and Algebraic Domain Modeling
Troubleshooting SQL Server: Un enfoque práctico
Ad

Viewers also liked (9)

PPTX
Javascript Common Design Patterns
PDF
JavaScript Prototype and Module Pattern
PDF
Javascript and DOM
PDF
Luận văn tìm hiểu Spring
PPTX
Trees (data structure)
PPTX
IoC and Mapper in C#
PDF
Prototype-based Programming with JavaScript
PPTX
Introduction to ajax
PPTX
Trees data structure
Javascript Common Design Patterns
JavaScript Prototype and Module Pattern
Javascript and DOM
Luận văn tìm hiểu Spring
Trees (data structure)
IoC and Mapper in C#
Prototype-based Programming with JavaScript
Introduction to ajax
Trees data structure
Ad

Similar to Javascript this keyword (20)

PPTX
Ian 20150116 java script oop
PPTX
Advanced JavaScript
PDF
PDF
Let's JavaScript
PDF
Say It With Javascript
KEY
Javascript tid-bits
PPTX
JavaScript - i och utanför webbläsaren (2010-03-03)
PDF
Object oriented JavaScript
PDF
Javascript
PPTX
Get started with YUI
PPTX
Advanced JavaScript
PPTX
4front en
PPT
Object Oriented JavaScript
PDF
JS Level Up: Prototypes
DOC
Jsphp 110312161301-phpapp02
PPTX
LinkedIn TBC JavaScript 100: Functions
PDF
JavaScript Execution Context
PDF
The many facets of code reuse in JavaScript
PDF
Advanced javascript
PPT
Function
Ian 20150116 java script oop
Advanced JavaScript
Let's JavaScript
Say It With Javascript
Javascript tid-bits
JavaScript - i och utanför webbläsaren (2010-03-03)
Object oriented JavaScript
Javascript
Get started with YUI
Advanced JavaScript
4front en
Object Oriented JavaScript
JS Level Up: Prototypes
Jsphp 110312161301-phpapp02
LinkedIn TBC JavaScript 100: Functions
JavaScript Execution Context
The many facets of code reuse in JavaScript
Advanced javascript
Function

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
master seminar digital applications in india
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Pre independence Education in Inndia.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
RMMM.pdf make it easy to upload and study
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Institutional Correction lecture only . . .
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Classroom Observation Tools for Teachers
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Anesthesia in Laparoscopic Surgery in India
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
master seminar digital applications in india
O7-L3 Supply Chain Operations - ICLT Program
Insiders guide to clinical Medicine.pdf
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pre independence Education in Inndia.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
RMMM.pdf make it easy to upload and study
TR - Agricultural Crops Production NC III.pdf
Institutional Correction lecture only . . .
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
Classroom Observation Tools for Teachers
Final Presentation General Medicine 03-08-2024.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF

Javascript this keyword