SlideShare a Scribd company logo
Bringing classical OOP into
JavaScript
By Dmitry Sheiko
Who's the dude?
I'm Dmitry Sheiko, a web developer, blogger,
open source contributor.
http://dsheiko.com
@sheiko
https://github.com/dsheiko
Eager to be a better coder?
Reading helps…
Reflecting learned patterns on JavaScript
What the hell?! Where are all the
classes, interfaces, members visibility,
namespaces, mixins?!
JavaScript is a class-free language
“JavaScript: The
World's Most
Misunderstood
Programming
Language”
Yet JavaScript is incredibly expressive
“The expressiveness of JavaScript provides
an enormous amount of power. Even
though the language lacks certain useful
built-in features, its flexibility allows you to
add them yourself…”
Ross Harmes, Dustin Diaz. Pro JavaScript Design Patterns
Make of JavaScript the language you need
As a class-based OOP programmer I would bring
to JavaScript following :
• classes with private/public members
• classical inheritance (abstract class -> class -> .. -> final class)
• interfaces
• mixins (traits)
• type hinting
• entry point validators
What look like objects in JavaScript
Somehow clumsy, isn’t it?
var o, SuperTypeConstruct = function() {}, ConstructorFunc = function() {
var _privateMember = "private member";
this.publicMember = "public member";
this.privilegedMethod = function() {
return _privateMember;
}
}
ConstructorFunc.prototype = new ConstructorFunc();
o = new ConstructorFunc();
What I want it to look like
var ConcreteClass = function() {
// Constructor's job
var _privateMember = "private member";
return {
__extends__: AbstractClass,
__implements__: [Countable, Traversable],
__mixin__: [Trait],
publicMember: "public member",
privilegedMethod: function() {
return _privateMember;
}
}
}
Can it inherit?
With a factory it can:
Function.prototype.createInstance = function () {
var key, module = this, members = module.apply(this, arguments),
Fn = function () {};
members.hasOwnProperty( "__extends__" ) && members[ "__extends__" ]
&& (module.prototype = members[ "__extends__" ].createInstance());
Fn.prototype = module.prototype; // Link to the supertype
for (key in members) { // Mix in members
if (members.hasOwnProperty(key)) {
Fn.prototype[key] = members[key];
}
}
return new Fn();
};
What about interfaces, mixins and so on?
We add with a hook any object creation
control flow that we wish. Let’s just change a
bit the factory:
Function.prototype.createInstance = function () {
...
instance = new Fn();
jsa.Hook.invokeAll( instance, arguments );
return instance;
};
JSA Way
JSA is a light-weight library comprising
factory plugins to “make of JavaScript the
language I want”. Let’s see what they are.
Widget foundation class
As good programmers we learn from the
great ones, don’t we? So, let’s borrow from
YUI guys some ideas of abstract widget
(http://yuilibrary.com/yui/docs/widget/) .
Videlicet:
• Common bootstrap interface
• Consistent node referencing
• Built-in progressive enhancement support
Widget abstract layer in JSA
Widget plugin declares BaseAbstract class,
which makes the factory (via a hook) to auto-
call bootstap methods (init, renderUI, syncUI)
of every class extending this one.
The plugin also declares WidgetAbstract, which
makes the factory to populate node property
with node references given in HTML_PARSER
property of extending class
+syncUI()
-__extends__
-HTML_PARSER
-settings
WidgetAbstract
+init()
+renderUI()
+syncUI()
BaseAbstract
+init()
+renderUI()
+syncUI()
-__extends__
-node
-settings
ConcreteModule
Usage example
(function( $, jsa ) {
Widget = function( settings ) {
// event handlers
_handler = {
onclick : function(e) {
// do something
}
};
return {
__extends__ : jsa.WidgetAbstract,
HTML_PARSER : {
toolbar : 'div.toolbar'
},
syncUI : function() {
this.node.toolbar.find( 'li' ).bind( 'click.intro', this, _handler.onclick );
}
};
};
$(document).bind( 'ready.app', function () { // Document is ready
Widget.createInstance({ boundingBox: $('div.intro') });
});
})( jQuery, jsa );
Mixins
Mixins provide aggregation
(has-a) relation between
objects, which is easy to
implement especially is
JavaScript. Mixin plugin only
assigns a hook, which makes
factory mix public members
of objects given in mixin
property
Mixin
+init()
+renderUI()
+syncUI()
-__extends__
-__mixin__
ConcreteClass
1
*
Usage example
var MixinA = {
propertyA: "propertyA"
},
MixinB = {
propertyB: "propertyB"
},
Silo = function() {
return {
__mixin__: [MixinA, MixinB ],
ownPropery: "Own property"
}
},
o = Silo.createInstance();
console.log(o.ownPropery !== undefined ); // true
console.log(o. propertyA !== undefined ); // true
console.log(o. propertyB !== undefined ); // true
Interfaces
Interface plugin assigns a hook,
which checks if the newly born
object meets the requirements of
the interfaces enlisted in
implement property. In order to
make sure arguments match type
hints, the plugin wrap the
method with cross-cutting
functionality, which does the
check on entry point.
-__implements__
ConcreteClass
Interface
*
Usage example
var ConcreteInterface = {
requeriedMethod : ["string”]
},
StrictModule = function() {
return {
__implements__: ConcreteInterface,
requeriedMethod : function() {
}
}
},
o = StrictModule.createInstance();
// Test
Module.requeriedMethod('a string'); // OK
Module.requeriedMethod(555); // throws TypeError exception
Design by Contract
Design by Contract approach
provides another and more
sophisticated solution of defining
requirements for the objects of a
type. By a contract we can define
entry/exit point conditions.
-__contract__
ConcereClass
Contract
*
var Contract = {
methodName: {
onEntry: [ "number", aClass ], // type hints
validators: [ function( arg ) {
return arg > 10;
}, secondArgValidator ],
onExit: "string"
}
}
Usage example
var ConcreteContract = {
methodA : {
onEntry: [ "number" ],
validators: [ function(arg){
return arg > 10;
} ],
onExit: "string"
}
},
EmployedModule = function() {
return {
__contract__: ConcreteContract,
aMethod : function() {
return "a string";
}
}
},
o = EmployedModule.createInstance();
o.aMethod( 50 ); // OK
o.aMethod( 1 ); // Validator fails, RangeError exception is thrown
Fork me!
JSA project page:
Articles relevant to JSA
http://dsheiko.com/weblog/js-application-design
http://dsheiko.com/weblog/prototypal-inheritance-
in-javascript-for-modules
http://dsheiko.com/weblog/design-by-contract-and-
js

More Related Content

What's hot

Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)
jeresig
 
Javascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to TitaniumJavascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to Titanium
Techday7
 
TypeScript 101
TypeScript 101TypeScript 101
TypeScript 101
rachelterman
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
Ivano Malavolta
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
Alessandro Giorgetti
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
Aniruddha Chakrabarti
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
Remo Jansen
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
Salvatore Fazio
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
Salvatore Fazio
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
Saai Vignesh P
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Alek Davis
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
Jussi Pohjolainen
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
raja kvk
 
Javascript Roadmap - The Basics
Javascript Roadmap - The BasicsJavascript Roadmap - The Basics
Javascript Roadmap - The Basics
Aswin Barath
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
TypeScript and Angular workshop
TypeScript and Angular workshopTypeScript and Angular workshop
TypeScript and Angular workshop
José Manuel García García
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 

What's hot (20)

Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)Advancing JavaScript with Libraries (Yahoo Tech Talk)
Advancing JavaScript with Libraries (Yahoo Tech Talk)
 
Javascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to TitaniumJavascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to Titanium
 
TypeScript 101
TypeScript 101TypeScript 101
TypeScript 101
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Javascript Roadmap - The Basics
Javascript Roadmap - The BasicsJavascript Roadmap - The Basics
Javascript Roadmap - The Basics
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
TypeScript and Angular workshop
TypeScript and Angular workshopTypeScript and Angular workshop
TypeScript and Angular workshop
 
Javascript
JavascriptJavascript
Javascript
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
 

Similar to Bringing classical OOP into JavaScript

Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Fabio Franzini
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
Melody Rios
 
Lezione 03 Introduzione a react
Lezione 03   Introduzione a reactLezione 03   Introduzione a react
Lezione 03 Introduzione a react
University of Catania
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
JavaScript
JavaScriptJavaScript
JavaScript
StrasWeb
 
J Query
J QueryJ Query
J Query
ravinxg
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for you
Simon Willison
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
anshunjain
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
Sergey Bolshchikov
 
Take control. write a plugin. part II
Take control. write a plugin. part IITake control. write a plugin. part II
Take control. write a plugin. part II
Baruch Sadogursky
 
Fewd week4 slides
Fewd week4 slidesFewd week4 slides
Fewd week4 slides
William Myers
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Mahmoud Tolba
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
Drupal 7 ci and testing
Drupal 7 ci and testingDrupal 7 ci and testing
Drupal 7 ci and testing
Claudio Beatrice
 
XWiki Rendering @ FOSDEM 2014
XWiki Rendering @ FOSDEM 2014XWiki Rendering @ FOSDEM 2014
XWiki Rendering @ FOSDEM 2014
Vincent Massol
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Lilia Sfaxi
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
Eliah Nikans
 

Similar to Bringing classical OOP into JavaScript (20)

Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjsCodemotion 2013 - Designing complex applications using html5 and knockoutjs
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
 
Lezione 03 Introduzione a react
Lezione 03   Introduzione a reactLezione 03   Introduzione a react
Lezione 03 Introduzione a react
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JavaScript
JavaScriptJavaScript
JavaScript
 
J Query
J QueryJ Query
J Query
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for you
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Take control. write a plugin. part II
Take control. write a plugin. part IITake control. write a plugin. part II
Take control. write a plugin. part II
 
Fewd week4 slides
Fewd week4 slidesFewd week4 slides
Fewd week4 slides
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
Drupal 7 ci and testing
Drupal 7 ci and testingDrupal 7 ci and testing
Drupal 7 ci and testing
 
XWiki Rendering @ FOSDEM 2014
XWiki Rendering @ FOSDEM 2014XWiki Rendering @ FOSDEM 2014
XWiki Rendering @ FOSDEM 2014
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 

More from Dmitry Sheiko

The Flavor of TypeScript
The Flavor of TypeScriptThe Flavor of TypeScript
The Flavor of TypeScript
Dmitry Sheiko
 
Writing Scalable and Maintainable CSS
Writing Scalable and Maintainable CSSWriting Scalable and Maintainable CSS
Writing Scalable and Maintainable CSS
Dmitry Sheiko
 
Tooling JavaScript to ensure consistency in coding style
Tooling JavaScript to ensure consistency in coding styleTooling JavaScript to ensure consistency in coding style
Tooling JavaScript to ensure consistency in coding style
Dmitry Sheiko
 
JavaScript MV* Framework - Making the Right Choice
JavaScript MV* Framework - Making the Right ChoiceJavaScript MV* Framework - Making the Right Choice
JavaScript MV* Framework - Making the Right Choice
Dmitry Sheiko
 
Modular JavaScript with CommonJS Compiler
Modular JavaScript with CommonJS CompilerModular JavaScript with CommonJS Compiler
Modular JavaScript with CommonJS Compiler
Dmitry Sheiko
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
A Quick Start - Version Control with Git
A Quick Start - Version Control with GitA Quick Start - Version Control with Git
A Quick Start - Version Control with Git
Dmitry Sheiko
 

More from Dmitry Sheiko (7)

The Flavor of TypeScript
The Flavor of TypeScriptThe Flavor of TypeScript
The Flavor of TypeScript
 
Writing Scalable and Maintainable CSS
Writing Scalable and Maintainable CSSWriting Scalable and Maintainable CSS
Writing Scalable and Maintainable CSS
 
Tooling JavaScript to ensure consistency in coding style
Tooling JavaScript to ensure consistency in coding styleTooling JavaScript to ensure consistency in coding style
Tooling JavaScript to ensure consistency in coding style
 
JavaScript MV* Framework - Making the Right Choice
JavaScript MV* Framework - Making the Right ChoiceJavaScript MV* Framework - Making the Right Choice
JavaScript MV* Framework - Making the Right Choice
 
Modular JavaScript with CommonJS Compiler
Modular JavaScript with CommonJS CompilerModular JavaScript with CommonJS Compiler
Modular JavaScript with CommonJS Compiler
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
A Quick Start - Version Control with Git
A Quick Start - Version Control with GitA Quick Start - Version Control with Git
A Quick Start - Version Control with Git
 

Recently uploaded

GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Containers & AI - Beauty and the Beast!?!
Containers & AI - Beauty and the Beast!?!Containers & AI - Beauty and the Beast!?!
Containers & AI - Beauty and the Beast!?!
Tobias Schneck
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
FilipTomaszewski5
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
ScyllaDB
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
Fwdays
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
AI in the Workplace Reskilling, Upskilling, and Future Work.pptx
AI in the Workplace Reskilling, Upskilling, and Future Work.pptxAI in the Workplace Reskilling, Upskilling, and Future Work.pptx
AI in the Workplace Reskilling, Upskilling, and Future Work.pptx
Sunil Jagani
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
AlexanderRichford
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Discover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched ContentDiscover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched Content
ScyllaDB
 

Recently uploaded (20)

GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Containers & AI - Beauty and the Beast!?!
Containers & AI - Beauty and the Beast!?!Containers & AI - Beauty and the Beast!?!
Containers & AI - Beauty and the Beast!?!
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
AI in the Workplace Reskilling, Upskilling, and Future Work.pptx
AI in the Workplace Reskilling, Upskilling, and Future Work.pptxAI in the Workplace Reskilling, Upskilling, and Future Work.pptx
AI in the Workplace Reskilling, Upskilling, and Future Work.pptx
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Discover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched ContentDiscover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched Content
 

Bringing classical OOP into JavaScript

  • 1. Bringing classical OOP into JavaScript By Dmitry Sheiko
  • 2. Who's the dude? I'm Dmitry Sheiko, a web developer, blogger, open source contributor. http://dsheiko.com @sheiko https://github.com/dsheiko
  • 3. Eager to be a better coder? Reading helps…
  • 4. Reflecting learned patterns on JavaScript What the hell?! Where are all the classes, interfaces, members visibility, namespaces, mixins?!
  • 5. JavaScript is a class-free language “JavaScript: The World's Most Misunderstood Programming Language”
  • 6. Yet JavaScript is incredibly expressive “The expressiveness of JavaScript provides an enormous amount of power. Even though the language lacks certain useful built-in features, its flexibility allows you to add them yourself…” Ross Harmes, Dustin Diaz. Pro JavaScript Design Patterns
  • 7. Make of JavaScript the language you need As a class-based OOP programmer I would bring to JavaScript following : • classes with private/public members • classical inheritance (abstract class -> class -> .. -> final class) • interfaces • mixins (traits) • type hinting • entry point validators
  • 8. What look like objects in JavaScript Somehow clumsy, isn’t it? var o, SuperTypeConstruct = function() {}, ConstructorFunc = function() { var _privateMember = "private member"; this.publicMember = "public member"; this.privilegedMethod = function() { return _privateMember; } } ConstructorFunc.prototype = new ConstructorFunc(); o = new ConstructorFunc();
  • 9. What I want it to look like var ConcreteClass = function() { // Constructor's job var _privateMember = "private member"; return { __extends__: AbstractClass, __implements__: [Countable, Traversable], __mixin__: [Trait], publicMember: "public member", privilegedMethod: function() { return _privateMember; } } }
  • 10. Can it inherit? With a factory it can: Function.prototype.createInstance = function () { var key, module = this, members = module.apply(this, arguments), Fn = function () {}; members.hasOwnProperty( "__extends__" ) && members[ "__extends__" ] && (module.prototype = members[ "__extends__" ].createInstance()); Fn.prototype = module.prototype; // Link to the supertype for (key in members) { // Mix in members if (members.hasOwnProperty(key)) { Fn.prototype[key] = members[key]; } } return new Fn(); };
  • 11. What about interfaces, mixins and so on? We add with a hook any object creation control flow that we wish. Let’s just change a bit the factory: Function.prototype.createInstance = function () { ... instance = new Fn(); jsa.Hook.invokeAll( instance, arguments ); return instance; };
  • 12. JSA Way JSA is a light-weight library comprising factory plugins to “make of JavaScript the language I want”. Let’s see what they are.
  • 13. Widget foundation class As good programmers we learn from the great ones, don’t we? So, let’s borrow from YUI guys some ideas of abstract widget (http://yuilibrary.com/yui/docs/widget/) . Videlicet: • Common bootstrap interface • Consistent node referencing • Built-in progressive enhancement support
  • 14. Widget abstract layer in JSA Widget plugin declares BaseAbstract class, which makes the factory (via a hook) to auto- call bootstap methods (init, renderUI, syncUI) of every class extending this one. The plugin also declares WidgetAbstract, which makes the factory to populate node property with node references given in HTML_PARSER property of extending class +syncUI() -__extends__ -HTML_PARSER -settings WidgetAbstract +init() +renderUI() +syncUI() BaseAbstract +init() +renderUI() +syncUI() -__extends__ -node -settings ConcreteModule
  • 15. Usage example (function( $, jsa ) { Widget = function( settings ) { // event handlers _handler = { onclick : function(e) { // do something } }; return { __extends__ : jsa.WidgetAbstract, HTML_PARSER : { toolbar : 'div.toolbar' }, syncUI : function() { this.node.toolbar.find( 'li' ).bind( 'click.intro', this, _handler.onclick ); } }; }; $(document).bind( 'ready.app', function () { // Document is ready Widget.createInstance({ boundingBox: $('div.intro') }); }); })( jQuery, jsa );
  • 16. Mixins Mixins provide aggregation (has-a) relation between objects, which is easy to implement especially is JavaScript. Mixin plugin only assigns a hook, which makes factory mix public members of objects given in mixin property Mixin +init() +renderUI() +syncUI() -__extends__ -__mixin__ ConcreteClass 1 *
  • 17. Usage example var MixinA = { propertyA: "propertyA" }, MixinB = { propertyB: "propertyB" }, Silo = function() { return { __mixin__: [MixinA, MixinB ], ownPropery: "Own property" } }, o = Silo.createInstance(); console.log(o.ownPropery !== undefined ); // true console.log(o. propertyA !== undefined ); // true console.log(o. propertyB !== undefined ); // true
  • 18. Interfaces Interface plugin assigns a hook, which checks if the newly born object meets the requirements of the interfaces enlisted in implement property. In order to make sure arguments match type hints, the plugin wrap the method with cross-cutting functionality, which does the check on entry point. -__implements__ ConcreteClass Interface *
  • 19. Usage example var ConcreteInterface = { requeriedMethod : ["string”] }, StrictModule = function() { return { __implements__: ConcreteInterface, requeriedMethod : function() { } } }, o = StrictModule.createInstance(); // Test Module.requeriedMethod('a string'); // OK Module.requeriedMethod(555); // throws TypeError exception
  • 20. Design by Contract Design by Contract approach provides another and more sophisticated solution of defining requirements for the objects of a type. By a contract we can define entry/exit point conditions. -__contract__ ConcereClass Contract * var Contract = { methodName: { onEntry: [ "number", aClass ], // type hints validators: [ function( arg ) { return arg > 10; }, secondArgValidator ], onExit: "string" } }
  • 21. Usage example var ConcreteContract = { methodA : { onEntry: [ "number" ], validators: [ function(arg){ return arg > 10; } ], onExit: "string" } }, EmployedModule = function() { return { __contract__: ConcreteContract, aMethod : function() { return "a string"; } } }, o = EmployedModule.createInstance(); o.aMethod( 50 ); // OK o.aMethod( 1 ); // Validator fails, RangeError exception is thrown
  • 22. Fork me! JSA project page: Articles relevant to JSA http://dsheiko.com/weblog/js-application-design http://dsheiko.com/weblog/prototypal-inheritance- in-javascript-for-modules http://dsheiko.com/weblog/design-by-contract-and- js