superclassy inheritance in javascript

Post on 11-May-2015

23.512 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

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

Superclassy Inheritancein Javascript

Alex Sexton

JavaScript Overview

Runs in more places than any other language.

JavaScript Overview

Troubled by the DOM and Newbz

JavaScript Overview

Simple but expressiveFunctional by nature, but not by syntax

JavaScript Overview

It _is_ Object Oriented –everything extends from Object

Bad Javascript

Not Reusable/Modular

Bad Javascript

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

Bad Javascript

Relies on the DOM (misusing jQuery, etc.)

Good JavaScript

ModularReusableReadable

Good JavaScript

Efficient

Good JavaScript

Stays out of the DOM (for the most part)

Types of Inheritance in JS

Classical Prototypal

Types of Inheritance in JS

Classical Prototypal

Pseudo-Classical

Types of Inheritance in JS

Classical Prototypal

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

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

-Douglas Crockford

Prototypal Inheritance

No Classes – just ObjectsObjects inherit from Objects

Prototypal Inheritance

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

Prototypal Inheritance

Prototypal Lineage

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

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

Pseudoclassical Inheritance

The syntax is Classical but behaves prototypally

Pseudoclassical Inheritance

3 Components to this pattern (the native pattern)

Constructor functions`new`Function.prototype

Pseudoclassical Inheritance

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

Constructor functions

Pseudoclassical Inheritance

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

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

Pseudoclassical Inheritance

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

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’);

Pseudoclassical Inheritance

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

It is REQUIRED.

Pseudoclassical Inheritance

This would be much like the prototypalway of doing:

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

Pseudoclassical Inheritance

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

Classical Inheritance

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

Classical Inheritance

Javascript is extremely versatileUsing a few simple tricks,

it’s easy to make believe

Classical Inheritance

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

This enables a new hierarchy.

Purely Prototypal

Very short and easy to mimic in Javascript

Native function in ECMAscript 5 (approved)

Gets rid of ‘new’ and constructor functions

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!

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…

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

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

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…

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

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

-Abe Lincoln

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.

Real Life

Your library may actually address the issue – or not…

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

-John Resig

Real Life

Build an API

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

A Badass Function

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

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);}

A Demo: Goals

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

in a clean mannerPretty code!

(switch to codez)

Fin.

Alex SextonAlexSexton@gmail.comhttp://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)

top related