SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
Classes and ‘this’
  Learning Javascript foundations


            John Hunter
             2 June 2009




                                    1
object properties
Unlike scope, properties assigned to an object do not have
lexical context. They belong to the object they are assigned
to.
However, they can be assigned to more than one object
...and they can be assigned very late.




                                                               2
this
    radio1                           radio1.getName();

                                           getName


    radio2                           radio2.getName();
                             this



Functions are data - they can be assigned as properties of
multiple objects (i.e. multiple references).
When the function is executed the 'this' property is
assigned the object from which it was called.

                                                             3
function getName () {

 console.log(this.name);   Function returns the name
}                                property of this.


window.name = 'Global';
getName();                    getName called in the
                             window (global) context
>>> Global

var radio1 = {

 name: 'radio one',

 getName: getName
};                            getName called in the
                                 radio1 context
radio1.getName();

>>> radio one
                                                        4
var radio1 = {

 name: 'radio one',

 getName: getName
};                     getName called in the
radio1.getName();         radio1 context

>>> radio one

var radio2 = {

 name: 'radio two',

 getName: getName
};                     getName called in the
                          radio2 context
radio2.getName();

>>> radio two
                                               5
Classes
In class based programming the class is a blueprint for objects.
First a class is defined and then instances of class can be
created.
Javascript does not directly support classes but can emulate
them.




                                                                   6
Classes
A class definition generally consists of:

 - a constructor
 - methods
Many languages have an explicit class definition that defines
both. In Javascript these are defined separately using
functions.


                                                              7
Constructor function
A constructor function is a function that:
  1. creates an instance object when called with new
  2. assigns properties to the new object this
  3. provides access to the prototype of the object

Note: Javascript cannot know which functions are going to be used as
constructors so all functions support these features.



                                                                       8
// Constructor
function ClassName (propertyValue) {
   this.instanceProperty = propertyValue;
}



// create an instance of the Class
var instance = new ClassName('my instance property');
console.log(instance. instanceProperty);


>>> my instance property


                                                        9
function getName () {

 console.log(this.name);
}

// Constructor
function RadioClass (name) {                   constructor binds
                                            getName function as an
   this.name = name;                            instance property
   this.getName = getName;
}

var radio2 = new RadioClass('radio two');
                                             getName returns the
radio2.getName();                              instance property

>>> radio two


                                                                     10
// Constructor
function RadioClass (name) {
   this.name = name;
   this.getName = function () {
                                              method is added as an

 
 console.log(this.name);                       instance property

 };
}                                             ✖ duplicated with each
                                                    instance created

// create an instance of the Class
var radio3 = new RadioClass('radio three');
radio3.getName();


>>> radio three


                                                                       11
// Constructor
function RadioClass (name) {
   this.name = name;
}

RadioClass.prototype.getName = function () {        method assigned to

 console.log(this.name);                      prototype object is inherited
                                                      by all instances
};

// create an instance of the Class
                                                  new creates a new this
var radio3 = new RadioClass('radio three');    object which inherits from
radio3.getName();                               the constructor prototype

>>> radio three


                                                                               12
RadioClass.prototype                   RadioClass constructor


 getName ()                                this.name



                                                       new
         2) look here   3) get this.name

                                                 radio1
                                                     radio2
                                                  radio3
                                           name = 'radio one'
                                              name = 'radio two'
                                            name = 'radio three'

                          1) look here
radio3.getName();

                                                                   13
Review
- this refers to the calling context of a function
- this is set at function invocation
- classes can be emulated using constructor functions
- calling new with a constructor returns an instance of this
- function.prototype provides an inheritance mechanism for
 instances to share methods


                                                               14
Thanks




         15

Contenu connexe

Tendances

คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
Finian Nian
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
Donal Fellows
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
mrecedu
 

Tendances (20)

Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
 
Adventures in TclOO
Adventures in TclOOAdventures in TclOO
Adventures in TclOO
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating Decorators
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31
 
Object - Oriented Programming Polymorphism
Object - Oriented Programming PolymorphismObject - Oriented Programming Polymorphism
Object - Oriented Programming Polymorphism
 
Revisão OCPJP7 - Class Design (parte 01)
Revisão OCPJP7 - Class Design (parte 01)Revisão OCPJP7 - Class Design (parte 01)
Revisão OCPJP7 - Class Design (parte 01)
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Class
ClassClass
Class
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 
Coffee Scriptでenchant.js
Coffee Scriptでenchant.jsCoffee Scriptでenchant.js
Coffee Scriptでenchant.js
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introduction
 
Extending ns
Extending nsExtending ns
Extending ns
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181
 

En vedette

Open Source Hardware for Dummies
Open Source Hardware for DummiesOpen Source Hardware for Dummies
Open Source Hardware for Dummies
Robert Viseur
 
Power example by Scott Kitchens
Power example by Scott KitchensPower example by Scott Kitchens
Power example by Scott Kitchens
Scott Kitchens
 
Legal analysis of source code
Legal analysis of source codeLegal analysis of source code
Legal analysis of source code
Robert Viseur
 
Identifying Success Factors for the Mozilla Project
Identifying Success Factors for the Mozilla ProjectIdentifying Success Factors for the Mozilla Project
Identifying Success Factors for the Mozilla Project
Robert Viseur
 

En vedette (16)

Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
 
Dad, I love You
Dad, I love YouDad, I love You
Dad, I love You
 
Open Source Hardware for Dummies
Open Source Hardware for DummiesOpen Source Hardware for Dummies
Open Source Hardware for Dummies
 
Power example by Scott Kitchens
Power example by Scott KitchensPower example by Scott Kitchens
Power example by Scott Kitchens
 
Javascript foundations: scope
Javascript foundations: scopeJavascript foundations: scope
Javascript foundations: scope
 
Look, We are not alone (how big you are, thing before pride)
Look, We are not alone (how big you are, thing before pride)Look, We are not alone (how big you are, thing before pride)
Look, We are not alone (how big you are, thing before pride)
 
Javascript foundations: Inheritance
Javascript foundations: InheritanceJavascript foundations: Inheritance
Javascript foundations: Inheritance
 
Javascript foundations: variables and types
Javascript foundations: variables and typesJavascript foundations: variables and types
Javascript foundations: variables and types
 
Jessicaspp
JessicasppJessicaspp
Jessicaspp
 
Ignite Opportunity 8by10
Ignite Opportunity 8by10Ignite Opportunity 8by10
Ignite Opportunity 8by10
 
L'écosystème régional du Big Data
L'écosystème régional du Big DataL'écosystème régional du Big Data
L'écosystème régional du Big Data
 
Legal analysis of source code
Legal analysis of source codeLegal analysis of source code
Legal analysis of source code
 
Identifying Success Factors for the Mozilla Project
Identifying Success Factors for the Mozilla ProjectIdentifying Success Factors for the Mozilla Project
Identifying Success Factors for the Mozilla Project
 
Comprendre les licences de logiciels libres
Comprendre les licences de logiciels libresComprendre les licences de logiciels libres
Comprendre les licences de logiciels libres
 
สรุปชื่อจริงจาว่า 4 ชื่อสุดท้าย
สรุปชื่อจริงจาว่า 4 ชื่อสุดท้ายสรุปชื่อจริงจาว่า 4 ชื่อสุดท้าย
สรุปชื่อจริงจาว่า 4 ชื่อสุดท้าย
 
Presentación caso de éxito Fernando Sarriá Jornadas OpenERP Bilbao
Presentación caso de éxito Fernando Sarriá Jornadas OpenERP BilbaoPresentación caso de éxito Fernando Sarriá Jornadas OpenERP Bilbao
Presentación caso de éxito Fernando Sarriá Jornadas OpenERP Bilbao
 

Similaire à Javascript foundations: Classes and `this`

1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf
archgeetsenterprises
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 

Similaire à Javascript foundations: Classes and `this` (20)

1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf1.what is the difference between a instance variable and an local va.pdf
1.what is the difference between a instance variable and an local va.pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdfphp_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
Js objects
Js objectsJs objects
Js objects
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
 
11slide
11slide11slide
11slide
 
JavaYDL11
JavaYDL11JavaYDL11
JavaYDL11
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
 
Java
JavaJava
Java
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Javascript foundations: Classes and `this`

  • 1. Classes and ‘this’ Learning Javascript foundations John Hunter 2 June 2009 1
  • 2. object properties Unlike scope, properties assigned to an object do not have lexical context. They belong to the object they are assigned to. However, they can be assigned to more than one object ...and they can be assigned very late. 2
  • 3. this radio1 radio1.getName(); getName radio2 radio2.getName(); this Functions are data - they can be assigned as properties of multiple objects (i.e. multiple references). When the function is executed the 'this' property is assigned the object from which it was called. 3
  • 4. function getName () { console.log(this.name); Function returns the name } property of this. window.name = 'Global'; getName(); getName called in the window (global) context >>> Global var radio1 = { name: 'radio one', getName: getName }; getName called in the radio1 context radio1.getName(); >>> radio one 4
  • 5. var radio1 = { name: 'radio one', getName: getName }; getName called in the radio1.getName(); radio1 context >>> radio one var radio2 = { name: 'radio two', getName: getName }; getName called in the radio2 context radio2.getName(); >>> radio two 5
  • 6. Classes In class based programming the class is a blueprint for objects. First a class is defined and then instances of class can be created. Javascript does not directly support classes but can emulate them. 6
  • 7. Classes A class definition generally consists of: - a constructor - methods Many languages have an explicit class definition that defines both. In Javascript these are defined separately using functions. 7
  • 8. Constructor function A constructor function is a function that: 1. creates an instance object when called with new 2. assigns properties to the new object this 3. provides access to the prototype of the object Note: Javascript cannot know which functions are going to be used as constructors so all functions support these features. 8
  • 9. // Constructor function ClassName (propertyValue) { this.instanceProperty = propertyValue; } // create an instance of the Class var instance = new ClassName('my instance property'); console.log(instance. instanceProperty); >>> my instance property 9
  • 10. function getName () { console.log(this.name); } // Constructor function RadioClass (name) { constructor binds getName function as an this.name = name; instance property this.getName = getName; } var radio2 = new RadioClass('radio two'); getName returns the radio2.getName(); instance property >>> radio two 10
  • 11. // Constructor function RadioClass (name) { this.name = name; this.getName = function () { method is added as an console.log(this.name); instance property }; } ✖ duplicated with each instance created // create an instance of the Class var radio3 = new RadioClass('radio three'); radio3.getName(); >>> radio three 11
  • 12. // Constructor function RadioClass (name) { this.name = name; } RadioClass.prototype.getName = function () { method assigned to console.log(this.name); prototype object is inherited by all instances }; // create an instance of the Class new creates a new this var radio3 = new RadioClass('radio three'); object which inherits from radio3.getName(); the constructor prototype >>> radio three 12
  • 13. RadioClass.prototype RadioClass constructor getName () this.name new 2) look here 3) get this.name radio1 radio2 radio3 name = 'radio one' name = 'radio two' name = 'radio three' 1) look here radio3.getName(); 13
  • 14. Review - this refers to the calling context of a function - this is set at function invocation - classes can be emulated using constructor functions - calling new with a constructor returns an instance of this - function.prototype provides an inheritance mechanism for instances to share methods 14
  • 15. Thanks 15