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

PDF
Paris Web - Javascript as a programming language
PDF
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
PDF
JavaScript Library Overview
PDF
PDF
Metaprogramming with javascript
PDF
TypeScript for Java Developers
PDF
Metaprogramming JavaScript
Paris Web - Javascript as a programming language
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
JavaScript Library Overview
Metaprogramming with javascript
TypeScript for Java Developers
Metaprogramming JavaScript

What's hot (20)

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

Similar to Bringing classical OOP into JavaScript (20)

PPTX
Framework prototype
PPTX
Framework prototype
PPTX
Framework prototype
PPTX
Inheritance Mixins & Traits
ODP
JavaScript Object Oriented Programming Cheat Sheet
PPTX
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
PDF
Unveiling Design Patterns: A Visual Guide with UML Diagrams
PDF
DesignPatternScard.pdf
PDF
Java script object model
PPTX
Object Oriented JavaScript - II
PDF
The Future of JavaScript (Ajax Exp '07)
PPT
Javascript Object Oriented Programming
PPTX
Javascript Object Patterns.pptx
PPTX
Does JavaScript Software Embrace Classes? (Talk at SANER 2015 Conference)
PPTX
Introduction to TypeScript
KEY
Javascript tid-bits
PDF
JavaScript OOPs
KEY
OOP in JS
PPTX
JavsScript OOP
PPTX
Type script by Howard
Framework prototype
Framework prototype
Framework prototype
Inheritance Mixins & Traits
JavaScript Object Oriented Programming Cheat Sheet
ECMA5 approach to building JavaScript frameworks with Anzor Bashkhaz
Unveiling Design Patterns: A Visual Guide with UML Diagrams
DesignPatternScard.pdf
Java script object model
Object Oriented JavaScript - II
The Future of JavaScript (Ajax Exp '07)
Javascript Object Oriented Programming
Javascript Object Patterns.pptx
Does JavaScript Software Embrace Classes? (Talk at SANER 2015 Conference)
Introduction to TypeScript
Javascript tid-bits
JavaScript OOPs
OOP in JS
JavsScript OOP
Type script by Howard
Ad

More from Dmitry Sheiko (7)

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

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Spectroscopy.pptx food analysis technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
A Presentation on Artificial Intelligence
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Unlocking AI with Model Context Protocol (MCP)
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Review of recent advances in non-invasive hemoglobin estimation
Spectroscopy.pptx food analysis technology
Machine learning based COVID-19 study performance prediction
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25-Week II
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
20250228 LYD VKU AI Blended-Learning.pptx
A Presentation on Artificial Intelligence

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