SlideShare a Scribd company logo
1 of 34
Object
patterns
Chapter 6 of The Principles of Object-Oriented JavaScript
‫العارف‬
‫عبد‬
‫الباسط‬
‫أبو‬
‫شعالة‬
1822294
‫تطبيقات‬
‫البرمجة‬
‫الهدفية‬
Table of content
1. Private and Privileged Members.
2. The Module Pattern.
3. Closure
4. Private members for constructors
5. Mixins
6. Scope-safe constructors
JavaScript has many patterns for
creating objects, You can define your
own custom types or your own generic
objects whenever you want,You can use
inheritance to share behavior between
objects,
or you can use mixins.
Now let’s understand Object patterns in
javascript more.
Introduction
Private and privileged
members
01
All object properties in JavaScript are public.
However, there are many ways of hiding data
that don’t rely on convention ways and are
therefore more reliable in preventing the
changing of private information.
Private and Privileged Members.
The module pattern
02
- It is a commonly used Design Pattern which is used to wrap a
set of variables and functions together in a single scope.
- The basic approach is to use an immediately invoked function
expression (IIFE) that returns an object.
The Module Pattern
An IIFE is a javascript function expression that runs as soon as it is
defined.
Note:All objects defined within the IIFE have access to the same
local variables.
Methods that access private data in this way are called privileged
methods
Immediately invoked function
expression (IIFE)
IIFE example
Note the Extra parentheses
at the end of the function
the function exists for
just a moment, is
executed, and then is
destroyed
Closure
03
Closures are functions that access data outside their own scope.
- A closure gives you access to an outer function’s scope from an
inner function.
- Closures are created every time a function is created, at
function creation time.
Closure
The difference with the module
function is that the variables are
declared within the IIFE, and a
function that is also declared inside
the IIFE accesses those variables. For
example:
Closure
Private Property
There is a variation of the module
pattern called the revealing module
pattern, which arranges all variables
and methods at the top of the IIFE
and simply assigns them to the
returned object. You can write the
previous example using the revealing
module pattern as follows:
module pattern
Private Members for
Constructor
04
Is there a way for defining custom types that also require their own
private properties?
Private Members for
Constructors
You can use a pattern that’s similar
to the module pattern inside the
constructor to create instance-
specific private data. For example:
Private Members
for
Constructors
you can use a hybrid approach if
you want private data to be shared
across all instances that looks like
the module pattern but uses a
constructor:
Mixins
04
Mixins occur when one object acquires the properties of another
without modifying the prototype chain.
- The first object (a receiver) actually receives the properties of
the second object (the supplier) by copying those properties
directly.
- You can also define mixins as a class containing methods that
can be used by other classes without a need to inherit from it.
Mixins
you create mixins using a function such as this:
Mixins
The mixin() function
accepts two arguments: the
receiver and the supplier.
The goal of the function is
to copy all enumerable
properties from the supplier
onto the receiver
You can use instances of EventTarget like this:
Mixins
If you want to have a different type of object that also
supports events, you have a few options. First, you can
create a new instance of EventTarget and then add on
the properties that you want:
Mixins
In this code, a new variable
called person is created as an
instance of EventTarget, and
then the person-related
properties are added.
Unfortunately, this means that
person is actually an instance
of EventTarget instead of
Object or a custom type
A second way to solve this problem is to use
pseudoclassical inheritance:
there is a new Person type that
inherits from EventTarget. You
can add any further methods
you need to Person’s prototype
afterward.
By using a mixin instead, you can reduce the amount of code
necessary to assign those new properties to the prototype:
Here, Person.prototype is
mixed in with a new instance of
EventTarget u to get the event
behavior. Then,
Person.prototype is mixed in
with constructor and
sayName() to complete the
composition of the prototype.
Instances of Person are not
instances of EventTarget in
this example because there is
no inheritance.
you might decide that while you do want to use an object’s properties, you don’t want
a constructor of pseudoclassical inheritance at all. In that case, you can use a mixin
directly when you create your new object:
In this example, a new
instance of EventTarget is
mixed in with some new
properties to create the person
object without affecting
person’s prototype chain.
One thing to keep in mind about using mixins in this way is that accessor properties on the
supplier become data properties on the receiver, which means you can overwrite them if
you’re not careful. That’s because the receiver properties are being created by assignment
rather than by Object.defineProperty(), meaning the current value of the supplier property
is read and then assigned to a property of the same name on the receiver. For example:
accessor property
This version of mixin() uses
Object.keys() u to get an array of
all enumerable own properties on
supplier. The forEach() method is
used to iterate over those
properties
Scope-Safe Constructors
05
Because all constructors are just functions, you can call them without using the new
operator and therefore affect the value of this. Doing so can yield unexpected results, as
this ends up coerced to the global object in nonstrict mode, or the constructor throws an
error in strict mode.
Scope-Safe Constructors
Scope-Safe Constructors
In this case, name is created
as a global variable because
the Person constructor is
called without new.
. In Chapter 4, you encountered this example:
Many built-in constructors,
such as Array and RegExp,
also work without new because
they are written to be scope
safe.
When new is called with a function, the newly created object
represented by this is already an instance of the custom type
represented by the constructor. So you can use instanceof to
determine whether new was used in the function call:
Using a pattern like this lets
you control what a function
does based on whether it’s
called with new or without. You
may want to treat each
circumstance differently
. A scope-safe version of Person looks like this
For this constructor, the name
property is assigned as always
when new is used. If new isn’t
used, the constructor is called
recursively via new to create a
proper instance of the object.
In this way, the following are equivalent:
Creating new objects without
using the new operator is
becoming more common as an
effort to curb errors caused by
omitting new. JavaScript itself
has several reference types
with scope-safe constructors,
such as Object, Array,
RegExp, and Error.
Thanks
‫العارف‬
‫عبد‬
‫الباسط‬
‫أبو‬
‫شعالة‬

More Related Content

Similar to Javascript Object Patterns.pptx

ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsSaurabh Narula
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsRahul Malhotra
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Applicationspeludner
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Inverting Dependencies
Inverting DependenciesInverting Dependencies
Inverting DependenciesLuc Trudeau
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through javaAditya Bhuyan
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad ideaPVS-Studio
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 

Similar to Javascript Object Patterns.pptx (20)

ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp concepts
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Layers of Smalltalk Application
Layers of Smalltalk ApplicationLayers of Smalltalk Application
Layers of Smalltalk Application
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Inverting Dependencies
Inverting DependenciesInverting Dependencies
Inverting Dependencies
 
Oops
OopsOops
Oops
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through java
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 

More from Alaref Abushaala

الطريق لكي تصبح مطور برمجيات.pptx
الطريق لكي تصبح مطور برمجيات.pptxالطريق لكي تصبح مطور برمجيات.pptx
الطريق لكي تصبح مطور برمجيات.pptxAlaref Abushaala
 
التخطيط لإختبار البرمجيات.pptx
التخطيط لإختبار البرمجيات.pptxالتخطيط لإختبار البرمجيات.pptx
التخطيط لإختبار البرمجيات.pptxAlaref Abushaala
 
Specialized parallel computing
Specialized parallel computingSpecialized parallel computing
Specialized parallel computingAlaref Abushaala
 
Travel guide app_prototyping_presentation
Travel guide app_prototyping_presentationTravel guide app_prototyping_presentation
Travel guide app_prototyping_presentationAlaref Abushaala
 
وحدة المعالجة المركزية
وحدة المعالجة المركزيةوحدة المعالجة المركزية
وحدة المعالجة المركزيةAlaref Abushaala
 
إدمان العصر الحديث
إدمان العصر الحديثإدمان العصر الحديث
إدمان العصر الحديثAlaref Abushaala
 
دور الاتصالات والتحكم الالي في تطور العالم
دور الاتصالات والتحكم الالي في تطور العالمدور الاتصالات والتحكم الالي في تطور العالم
دور الاتصالات والتحكم الالي في تطور العالمAlaref Abushaala
 
منظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظممنظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظمAlaref Abushaala
 
منظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظممنظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظمAlaref Abushaala
 

More from Alaref Abushaala (10)

الطريق لكي تصبح مطور برمجيات.pptx
الطريق لكي تصبح مطور برمجيات.pptxالطريق لكي تصبح مطور برمجيات.pptx
الطريق لكي تصبح مطور برمجيات.pptx
 
Distributed Database
Distributed Database Distributed Database
Distributed Database
 
التخطيط لإختبار البرمجيات.pptx
التخطيط لإختبار البرمجيات.pptxالتخطيط لإختبار البرمجيات.pptx
التخطيط لإختبار البرمجيات.pptx
 
Specialized parallel computing
Specialized parallel computingSpecialized parallel computing
Specialized parallel computing
 
Travel guide app_prototyping_presentation
Travel guide app_prototyping_presentationTravel guide app_prototyping_presentation
Travel guide app_prototyping_presentation
 
وحدة المعالجة المركزية
وحدة المعالجة المركزيةوحدة المعالجة المركزية
وحدة المعالجة المركزية
 
إدمان العصر الحديث
إدمان العصر الحديثإدمان العصر الحديث
إدمان العصر الحديث
 
دور الاتصالات والتحكم الالي في تطور العالم
دور الاتصالات والتحكم الالي في تطور العالمدور الاتصالات والتحكم الالي في تطور العالم
دور الاتصالات والتحكم الالي في تطور العالم
 
منظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظممنظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظم
 
منظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظممنظومة إدارة السجناء | تحليل وتصميم نظم
منظومة إدارة السجناء | تحليل وتصميم نظم
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 

Javascript Object Patterns.pptx

  • 1. Object patterns Chapter 6 of The Principles of Object-Oriented JavaScript ‫العارف‬ ‫عبد‬ ‫الباسط‬ ‫أبو‬ ‫شعالة‬ 1822294 ‫تطبيقات‬ ‫البرمجة‬ ‫الهدفية‬
  • 2. Table of content 1. Private and Privileged Members. 2. The Module Pattern. 3. Closure 4. Private members for constructors 5. Mixins 6. Scope-safe constructors
  • 3. JavaScript has many patterns for creating objects, You can define your own custom types or your own generic objects whenever you want,You can use inheritance to share behavior between objects, or you can use mixins. Now let’s understand Object patterns in javascript more. Introduction
  • 5. All object properties in JavaScript are public. However, there are many ways of hiding data that don’t rely on convention ways and are therefore more reliable in preventing the changing of private information. Private and Privileged Members.
  • 7. - It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope. - The basic approach is to use an immediately invoked function expression (IIFE) that returns an object. The Module Pattern
  • 8. An IIFE is a javascript function expression that runs as soon as it is defined. Note:All objects defined within the IIFE have access to the same local variables. Methods that access private data in this way are called privileged methods Immediately invoked function expression (IIFE)
  • 9. IIFE example Note the Extra parentheses at the end of the function the function exists for just a moment, is executed, and then is destroyed
  • 11. Closures are functions that access data outside their own scope. - A closure gives you access to an outer function’s scope from an inner function. - Closures are created every time a function is created, at function creation time. Closure
  • 12. The difference with the module function is that the variables are declared within the IIFE, and a function that is also declared inside the IIFE accesses those variables. For example: Closure Private Property
  • 13. There is a variation of the module pattern called the revealing module pattern, which arranges all variables and methods at the top of the IIFE and simply assigns them to the returned object. You can write the previous example using the revealing module pattern as follows: module pattern
  • 15. Is there a way for defining custom types that also require their own private properties? Private Members for Constructors
  • 16. You can use a pattern that’s similar to the module pattern inside the constructor to create instance- specific private data. For example: Private Members for Constructors
  • 17. you can use a hybrid approach if you want private data to be shared across all instances that looks like the module pattern but uses a constructor:
  • 19. Mixins occur when one object acquires the properties of another without modifying the prototype chain. - The first object (a receiver) actually receives the properties of the second object (the supplier) by copying those properties directly. - You can also define mixins as a class containing methods that can be used by other classes without a need to inherit from it. Mixins
  • 20. you create mixins using a function such as this: Mixins The mixin() function accepts two arguments: the receiver and the supplier. The goal of the function is to copy all enumerable properties from the supplier onto the receiver
  • 21. You can use instances of EventTarget like this: Mixins
  • 22. If you want to have a different type of object that also supports events, you have a few options. First, you can create a new instance of EventTarget and then add on the properties that you want: Mixins In this code, a new variable called person is created as an instance of EventTarget, and then the person-related properties are added. Unfortunately, this means that person is actually an instance of EventTarget instead of Object or a custom type
  • 23. A second way to solve this problem is to use pseudoclassical inheritance: there is a new Person type that inherits from EventTarget. You can add any further methods you need to Person’s prototype afterward.
  • 24. By using a mixin instead, you can reduce the amount of code necessary to assign those new properties to the prototype: Here, Person.prototype is mixed in with a new instance of EventTarget u to get the event behavior. Then, Person.prototype is mixed in with constructor and sayName() to complete the composition of the prototype. Instances of Person are not instances of EventTarget in this example because there is no inheritance.
  • 25. you might decide that while you do want to use an object’s properties, you don’t want a constructor of pseudoclassical inheritance at all. In that case, you can use a mixin directly when you create your new object: In this example, a new instance of EventTarget is mixed in with some new properties to create the person object without affecting person’s prototype chain.
  • 26. One thing to keep in mind about using mixins in this way is that accessor properties on the supplier become data properties on the receiver, which means you can overwrite them if you’re not careful. That’s because the receiver properties are being created by assignment rather than by Object.defineProperty(), meaning the current value of the supplier property is read and then assigned to a property of the same name on the receiver. For example: accessor property
  • 27. This version of mixin() uses Object.keys() u to get an array of all enumerable own properties on supplier. The forEach() method is used to iterate over those properties
  • 29. Because all constructors are just functions, you can call them without using the new operator and therefore affect the value of this. Doing so can yield unexpected results, as this ends up coerced to the global object in nonstrict mode, or the constructor throws an error in strict mode. Scope-Safe Constructors
  • 30. Scope-Safe Constructors In this case, name is created as a global variable because the Person constructor is called without new. . In Chapter 4, you encountered this example: Many built-in constructors, such as Array and RegExp, also work without new because they are written to be scope safe.
  • 31. When new is called with a function, the newly created object represented by this is already an instance of the custom type represented by the constructor. So you can use instanceof to determine whether new was used in the function call: Using a pattern like this lets you control what a function does based on whether it’s called with new or without. You may want to treat each circumstance differently
  • 32. . A scope-safe version of Person looks like this For this constructor, the name property is assigned as always when new is used. If new isn’t used, the constructor is called recursively via new to create a proper instance of the object.
  • 33. In this way, the following are equivalent: Creating new objects without using the new operator is becoming more common as an effort to curb errors caused by omitting new. JavaScript itself has several reference types with scope-safe constructors, such as Object, Array, RegExp, and Error.