superclassy inheritance in javascript

51
Superclassy Inheritance in Javascript Alex Sexton

Upload: alex-sexton

Post on 11-May-2015

23.512 views

Category:

Technology


1 download

DESCRIPTION

Superclassy Inheritance with JavaScript is a quick look at the benefits and consequences of several inheritance patterns in JavaScript. Code reuse plays a major role in the DRY development pattern and leveraging the inheritance patterns built into JavaScript or manipulating them can change the way you build and organize large applications. Unfortunately, JavaScript's reputation and odd naming scheme have stopped people from using all the features that it has to offer. First, we'll discuss the array of options that exist and then go through a real-world example while using our newly honed inheritance-foo to make it play nice.

TRANSCRIPT

Page 1: Superclassy Inheritance In Javascript

Superclassy Inheritancein Javascript

Alex Sexton

Page 2: Superclassy Inheritance In Javascript

JavaScript Overview

Runs in more places than any other language.

Page 3: Superclassy Inheritance In Javascript

JavaScript Overview

Troubled by the DOM and Newbz

Page 4: Superclassy Inheritance In Javascript

JavaScript Overview

Simple but expressiveFunctional by nature, but not by syntax

Page 5: Superclassy Inheritance In Javascript

JavaScript Overview

It _is_ Object Oriented –everything extends from Object

Page 6: Superclassy Inheritance In Javascript

Bad Javascript

Not Reusable/Modular

Page 7: Superclassy Inheritance In Javascript

Bad Javascript

Hard to read(let’s leave nests to birds and aging mothers)

Page 8: Superclassy Inheritance In Javascript

Bad Javascript

Relies on the DOM (misusing jQuery, etc.)

Page 9: Superclassy Inheritance In Javascript
Page 10: Superclassy Inheritance In Javascript

Good JavaScript

ModularReusableReadable

Page 11: Superclassy Inheritance In Javascript

Good JavaScript

Efficient

Page 12: Superclassy Inheritance In Javascript

Good JavaScript

Stays out of the DOM (for the most part)

Page 13: Superclassy Inheritance In Javascript
Page 14: Superclassy Inheritance In Javascript

Types of Inheritance in JS

Classical Prototypal

Page 15: Superclassy Inheritance In Javascript

Types of Inheritance in JS

Classical Prototypal

Pseudo-Classical

Page 16: Superclassy Inheritance In Javascript

Types of Inheritance in JS

Classical Prototypal

Pseudo-Classical^----native (kind of)

Page 17: Superclassy Inheritance In Javascript

“It doesn't matter what an object's lineage is, what matters is the quality of its contents.”

-Douglas Crockford

Page 18: Superclassy Inheritance In Javascript

Prototypal Inheritance

No Classes – just ObjectsObjects inherit from Objects

Page 19: Superclassy Inheritance In Javascript

Prototypal Inheritance

Objects contain a “link” to another objectThe “parent” Object is just a regular Object!

Page 20: Superclassy Inheritance In Javascript

Prototypal Inheritance

Page 21: Superclassy Inheritance In Javascript

Prototypal Lineage

Changes in oldObject bubble to newObjectChanges in newObject do not affect oldObject

Page 22: Superclassy Inheritance In Javascript

Prototypal Lineage

Theoretically can go on forever —(you shouldn’t need more than a few levels)

Differential Inheritance is fast (common-case)

and memory efficient

Page 23: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

The syntax is Classical but behaves prototypally

Page 24: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

3 Components to this pattern (the native pattern)

Constructor functions`new`Function.prototype

Page 25: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

Classes in this pattern should be capitalizedClasses are named/defined by their

Constructor functions

Page 26: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

function Constructor (){ this.instance_member = …; // automatically returns `this` when invoked

// with the `new` operator } var myObject = new Constructor();

Page 27: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

Methods and properties that are intended to be inherited are added to the function’s ‘prototype’

Page 28: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

The code inside the function is there to help ‘set up’ or ‘construct’ the returned object

function Constructor(val){ this.val = val; }

Constructor.prototype.method1 = function(){…};

Constructor.prototype.staticVal = 100; var newObject = new Constructor(‘val’);

Page 29: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

The ‘new’ operator creates a new object, with a link back to its parent’s prototype object.

It is REQUIRED.

Page 30: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

This would be much like the prototypalway of doing:

// prototypal equivalentvar newObject = Object.create(Constructor.prototype);

Page 31: Superclassy Inheritance In Javascript

Pseudoclassical Inheritance

// prototypal equivalentvar newObject = Object.create(Constructor.prototype);

Page 32: Superclassy Inheritance In Javascript

Classical Inheritance

At it’s core, Javascript is prototypal, and does not support the Classical model

Page 33: Superclassy Inheritance In Javascript

Classical Inheritance

Javascript is extremely versatileUsing a few simple tricks,

it’s easy to make believe

Page 34: Superclassy Inheritance In Javascript

Classical Inheritance

The ‘key’ is that any Objects ‘prototype’ member is mutable and can be replaced with another object.

This enables a new hierarchy.

Page 35: Superclassy Inheritance In Javascript

Purely Prototypal

Very short and easy to mimic in Javascript

Native function in ECMAscript 5 (approved)

Gets rid of ‘new’ and constructor functions

Page 36: Superclassy Inheritance In Javascript

Purely Prototypal

if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); };}

var newObject = Object.create(OldObject); //yay!

Page 37: Superclassy Inheritance In Javascript

Classical Inheritance in Javascript

A little tougher to implement, but there are plenty already written

simple-inheritance | MooTools Class | Prototype Class | Lowpro | Base2 |Way More…

Page 38: Superclassy Inheritance In Javascript

Classical Inheritance in Javascript

There is a small penalty in overhead since it’s not all native, but generally still fairly quick

Enhanced API gives easier access to the superclasses methods and often more

Easier than teaching old dogs new tricks

Page 39: Superclassy Inheritance In Javascript

simple-inheritance (api) by John Resig

but pretty much stolen from Prototype and Base2

var Person = Class.extend({  init: function(isDancing){    this.dancing = isDancing;  },  dance: function(){    return this.dancing;  }

});var Ninja = Person.extend({

  init: function(){    this._super( false ); // SEE?!!! SUPER CLASSY!  },  dance: function(){    // Call the inherited version of dance()    return this._super();  },  swingSword: function(){    return true;  }

});var p = new Person(true);p.dance(); // => truevar n = new Ninja();n.dance(); // => falsen.swingSword(); // => true// Should all be truep instanceof Person && p instanceof Class &&n instanceof Ninja && n instanceof Person && n instanceof Class

Page 40: Superclassy Inheritance In Javascript

Information Hiding

Use the “Module Pattern” – a function that takes advantage of closures and returns an object with access to private information that isn’t available outside of the function scope.

Or something…

Page 41: Superclassy Inheritance In Javascript

The Module Pattern

function module(){ var privateFunction = function() { return “private”; }; return { publicFunction: function(){ return “public: “ + privateFunction(); } };}var newModule = Object.create(module());newModule.publicFunction(); // “public: private”newModule.privateFunction(); // error

// Great for Getters and Setters of member values

Page 42: Superclassy Inheritance In Javascript

“But this doesn’t apply to my real life applications with X Library or Y Scripts!”

-Abe Lincoln

Page 43: Superclassy Inheritance In Javascript

Real Life

Rofl… that’s not a real quote guys…

It fits just fine. Stop trying to use the DOM as your point of access for everything.

Page 44: Superclassy Inheritance In Javascript

Real Life

Your library may actually address the issue – or not…

Page 45: Superclassy Inheritance In Javascript

“I just think that the intersection between jQuery and classical inheritance is quite small.”

-John Resig

Page 46: Superclassy Inheritance In Javascript

Real Life

Build an API

Speakers should ‘speak()’ not append text to DOM elements

Page 47: Superclassy Inheritance In Javascript

A Badass Function

I like to call it “Stolen Identity” – it shows how versatile Javascript really is when it comes to inheritance

Page 48: Superclassy Inheritance In Javascript

A Badass Function

// example from Stoyan Stefanov for YUI inheritance

// Steal the member variables along with the prototype

function Programmer() { // initialize the parent using the child as "this" Programmer.superclass.constructor.apply(this,

arguments);}

Page 49: Superclassy Inheritance In Javascript

A Demo: Goals

Use inheritance(s) along with a frameworkTie the DOM and the Object together

in a clean mannerPretty code!

Page 50: Superclassy Inheritance In Javascript

(switch to codez)

Page 51: Superclassy Inheritance In Javascript

Fin.

Alex [email protected]://twitter.com/slexaxton

http://alexsexton.com/inheritance/demo/http://yayquery.com/

Special Thanks to:Douglas CrockfordJohn ResigStoyan StefanovPrototype | Base2 | Dojo | jQuery etc…#jquery on irc.freenode.net

(YAYQUERY == Paul Irish, Rebecca Murphey, Adam Sontag)