SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
this
is simple

Nir Elbaz, 2013

1
this is a JavaScript language immutable variable

Nir Elbaz, 2013

2
Usually, this refers to the object which owns
the method it was called from

Nir Elbaz, 2013

3
this === window (global context)

// no current object - window object owns it all:
var strText = "Hello, world";
alert(strText);
alert(window.strText);
alert(this.strText);

// -> "Hello, world"
// -> again, "Hello, world"
// -> and again, "Hello, world"

Nir Elbaz, 2013

4
this === window (global context)

// callingThis method is owned by window object:
var strText = "Hello, world";
function callingThis () {
alert(strText);
alert(window.strText);
alert(this.strText);
}

// -> "Hello, world"
// -> again, "Hello, world"
// -> and again, "Hello, world"

callingThis();

Nir Elbaz, 2013

5
this === undefined

// adding “use strict” to a function will cause this to be undefined:
var strText = "Hello, world";
function callingThis () {
"use strict";
alert(strText);
alert(window.strText);
alert(this.strText);
}

// -> "Hello, world"
// -> again, "Hello, world"
// -> nothing is shown since this === undefined

callingThis();

Nir Elbaz, 2013

6
this === Object
// callingThis, callingThat & callingThatAgain methods are now owned by
// MainObject object:
this.strText = "Hello, world";
function MainObject () {
this.strText = "I belong to MainObject";
this.callingThis = function () {
alert(this.strText);
}
}
MainObject.prototype.callingThat = function () {
alert(this.strText);
}
function alertText () {
alert(this.strText);
}
var obj = new MainObject();
obj.callingThis();
// -> "I belong to mainObject"
obj.callingThat();
// -> again, "I belong to mainObject"
obj.callingThatAgain = alertText;
obj.callingThatAgain();
// -> and Nir Elbaz, 2013 belong to mainObject"
again, "I
alert(this.strText);
// -> "Hello, world"
alertText();
// -> again, "Hello, world"

7
this === Object
// using bind, apply & call to define this:
var strText = "Hello, world";
function callingThis () {
alert(this.strText);
}
function MyObject () {
this.strText = "I belong to MainObject";
}
CallingThis();
var myObject = new MyObject();
callingThis.apply(myObject);
callingThis.call(myObject);
callingThis.bind(myObject);

// -> "Hello, world"
// -> "I belong to mainObject"
// -> again, "I belong to mainObject"
// -> and again, "I belong to mainObject"

Nir Elbaz, 2013

8
this === Object... and window!
// in ECMA 3, -this- refers to the head object in nested functions:
var MyObject = {
func1: function () {
console.log(this); // logs MyObject
var func2 = function () {
console.log(this); // logs window, and will do so from this point on
var func3 = function () {
console.log(this); // logs window, as it’s the head object
}();
}();
}
};
MyObject.func1();

Nir Elbaz, 2013

9
this === Object
// ECMA 5 fixed this behavior, or - you can fix it by sending -this- as a param
var MyObject = {
func1: function () {
console.log(this);
// logs MyObject
var func2 = function (self) {
console.log(self);
// logs MyObject
var func3 = function (self) {
console.log(self); // logs MyObject
}(self);
}(this);
}
};
MyObject.func1();

Nir Elbaz, 2013

10
this === DOM Element
// when a function is used as an event handler, its -this- is set to the element
// the event fired from, also in an inline event handler
var paragraphs = document.getElementsByTagName('p');
for (var i = 0, j = paragraphs.length; i < j; i++) {
paragraphs[i].addEventListener('click', function () {
console.log(this); // logs the element the event fired from
}, false)
}
<button onclick="console.log(this);">Log this</button>

Nir Elbaz, 2013

11
Summary
When not using call / apply or bind, the this value
will always refer to the global context, except in the
following instances:
✔

✔

The function was called with the new operator, in which
case this points to a new object
The function is a member of an object, in which case
this points to the object UNLESS function is being
called asynchronously.
- Yehuda Katz
Nir Elbaz, 2013

12
Resources
●

Fully Understanding the this Keyword

●

What is ‘this’ in JavaScript?

●

this

●

Understanding “Prototypes” in JavaScript

http://nirelbaz.tumblr.com

Nir Elbaz, 2013

13

Mais conteúdo relacionado

Mais procurados

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 

Mais procurados (20)

AngularJs , How it works
AngularJs , How it worksAngularJs , How it works
AngularJs , How it works
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 
AnyObject – 自分が見落としていた、基本の話
AnyObject – 自分が見落としていた、基本の話AnyObject – 自分が見落としていた、基本の話
AnyObject – 自分が見落としていた、基本の話
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
 
Groovify your java code by hervé roussel
Groovify your java code by hervé rousselGroovify your java code by hervé roussel
Groovify your java code by hervé roussel
 
Presenting things in Swift
Presenting things in SwiftPresenting things in Swift
Presenting things in Swift
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Example sas code for ICC calculation and timeseries analysis
Example sas code for ICC calculation and timeseries analysisExample sas code for ICC calculation and timeseries analysis
Example sas code for ICC calculation and timeseries analysis
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Json.parse() in JavaScript
Json.parse() in JavaScriptJson.parse() in JavaScript
Json.parse() in JavaScript
 
Functional Reactive Programming - RxSwift
Functional Reactive Programming - RxSwiftFunctional Reactive Programming - RxSwift
Functional Reactive Programming - RxSwift
 
Function
FunctionFunction
Function
 
Constructor in detail
Constructor in detailConstructor in detail
Constructor in detail
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 

Semelhante a this is simple

The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
timotheeg
 

Semelhante a this is simple (20)

Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Javascript
JavascriptJavascript
Javascript
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.
JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.
JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Java script
Java scriptJava script
Java script
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015
 

Mais de Nir Elbaz (6)

Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
 
Hello, AngularJS 1.3
Hello, AngularJS 1.3Hello, AngularJS 1.3
Hello, AngularJS 1.3
 
Dalek.js - Automated cross browser testing with JavaScript
Dalek.js - Automated cross browser testing with JavaScriptDalek.js - Automated cross browser testing with JavaScript
Dalek.js - Automated cross browser testing with JavaScript
 
IBM Worklight
IBM WorklightIBM Worklight
IBM Worklight
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Introduction to html 5
Introduction to html 5Introduction to html 5
Introduction to html 5
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

this is simple

  • 2. this is a JavaScript language immutable variable Nir Elbaz, 2013 2
  • 3. Usually, this refers to the object which owns the method it was called from Nir Elbaz, 2013 3
  • 4. this === window (global context) // no current object - window object owns it all: var strText = "Hello, world"; alert(strText); alert(window.strText); alert(this.strText); // -> "Hello, world" // -> again, "Hello, world" // -> and again, "Hello, world" Nir Elbaz, 2013 4
  • 5. this === window (global context) // callingThis method is owned by window object: var strText = "Hello, world"; function callingThis () { alert(strText); alert(window.strText); alert(this.strText); } // -> "Hello, world" // -> again, "Hello, world" // -> and again, "Hello, world" callingThis(); Nir Elbaz, 2013 5
  • 6. this === undefined // adding “use strict” to a function will cause this to be undefined: var strText = "Hello, world"; function callingThis () { "use strict"; alert(strText); alert(window.strText); alert(this.strText); } // -> "Hello, world" // -> again, "Hello, world" // -> nothing is shown since this === undefined callingThis(); Nir Elbaz, 2013 6
  • 7. this === Object // callingThis, callingThat & callingThatAgain methods are now owned by // MainObject object: this.strText = "Hello, world"; function MainObject () { this.strText = "I belong to MainObject"; this.callingThis = function () { alert(this.strText); } } MainObject.prototype.callingThat = function () { alert(this.strText); } function alertText () { alert(this.strText); } var obj = new MainObject(); obj.callingThis(); // -> "I belong to mainObject" obj.callingThat(); // -> again, "I belong to mainObject" obj.callingThatAgain = alertText; obj.callingThatAgain(); // -> and Nir Elbaz, 2013 belong to mainObject" again, "I alert(this.strText); // -> "Hello, world" alertText(); // -> again, "Hello, world" 7
  • 8. this === Object // using bind, apply & call to define this: var strText = "Hello, world"; function callingThis () { alert(this.strText); } function MyObject () { this.strText = "I belong to MainObject"; } CallingThis(); var myObject = new MyObject(); callingThis.apply(myObject); callingThis.call(myObject); callingThis.bind(myObject); // -> "Hello, world" // -> "I belong to mainObject" // -> again, "I belong to mainObject" // -> and again, "I belong to mainObject" Nir Elbaz, 2013 8
  • 9. this === Object... and window! // in ECMA 3, -this- refers to the head object in nested functions: var MyObject = { func1: function () { console.log(this); // logs MyObject var func2 = function () { console.log(this); // logs window, and will do so from this point on var func3 = function () { console.log(this); // logs window, as it’s the head object }(); }(); } }; MyObject.func1(); Nir Elbaz, 2013 9
  • 10. this === Object // ECMA 5 fixed this behavior, or - you can fix it by sending -this- as a param var MyObject = { func1: function () { console.log(this); // logs MyObject var func2 = function (self) { console.log(self); // logs MyObject var func3 = function (self) { console.log(self); // logs MyObject }(self); }(this); } }; MyObject.func1(); Nir Elbaz, 2013 10
  • 11. this === DOM Element // when a function is used as an event handler, its -this- is set to the element // the event fired from, also in an inline event handler var paragraphs = document.getElementsByTagName('p'); for (var i = 0, j = paragraphs.length; i < j; i++) { paragraphs[i].addEventListener('click', function () { console.log(this); // logs the element the event fired from }, false) } <button onclick="console.log(this);">Log this</button> Nir Elbaz, 2013 11
  • 12. Summary When not using call / apply or bind, the this value will always refer to the global context, except in the following instances: ✔ ✔ The function was called with the new operator, in which case this points to a new object The function is a member of an object, in which case this points to the object UNLESS function is being called asynchronously. - Yehuda Katz Nir Elbaz, 2013 12
  • 13. Resources ● Fully Understanding the this Keyword ● What is ‘this’ in JavaScript? ● this ● Understanding “Prototypes” in JavaScript http://nirelbaz.tumblr.com Nir Elbaz, 2013 13