Skip to content

Instantly share code, notes, and snippets.

@arcanis
Created May 18, 2012 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arcanis/2724085 to your computer and use it in GitHub Desktop.
Save arcanis/2724085 to your computer and use it in GitHub Desktop.
Classes en javascript
// Chaque fonction est un constructeur
var Foo = function ( ) { this.bar = 'hello world'; };
var instance = new Foo( );
console.log( instance.bar ); // "hello world"
// Chaque fonction possède un prototype
var Foo = function ( ) { };
Foo.prototype.bar = 'hello world';
var instance = new Foo( );
console.log( instance.bar ); // "hello world"
// Chaque prototype peut être mis à jour 'en temps réel'
var Foo = function ( ) { };
Foo.prototype.bar = 'hello world';
var instance = new Foo( );
Foo.prototype.bar = 'haxxed';
console.log( instance.bar ); // "haxxed"
// Un début d'héritage
var Foo = function ( ) { };
Foo.prototype.hello = function ( ) { return 42; };
var Bar = function ( ) { };
Bar.prototype = Foo.prototype;
Bar.prototype.hellodbl = function ( ) { return this.hello( ) * 2; };
// Ne fonctionne pas : le prototype de Foo a aussi été modifié
// Car Foo.prototype === Bar.prototype
// Une suite d'héritage
var Foo = function ( ) { };
Foo.prototype.hello = function ( ) { return 42; };
var Bar = function ( ) { };
Bar.prototype = new Foo( );
Bar.prototype.hellodbl = function ( ) { return this.hello( ) * 2; };
// Mieux : l'objet Bar.prototype est une nouvelle instance, donc si on le modifie
// cela n'affectera pas Foo.prototype.
// Un meilleur héritage
var Foo = function ( ) { /* plein de code */ };
Foo.prototype.hello = function ( ) { return 42; };
var F = function ( ) { };
F.prototype = Bar.prototype;
var Bar = function ( ) { };
Bar.prototype = new F( );
Bar.prototype.hellodbl = function ( ) { return this.hello( ) * 2; };
// Pourquoi passer par une fonction F() ? Car cela éviter d'appeller le
// constructeur de la classe Foo lors de la définition de l'héritage. Si
// on ne l'avait pas fait, le "plein de code" de la ligne 40 aurait été
// executé.
// Appel au constructeur parent
var Foo = function ( ) { /* plein de code */ };
var F = function ( ) { };
F.prototype = Foo.prototype;
var Bar = function ( ) { Foo.call( this ); };
Bar.prototype = new F( );
// Function.call appelle une fonction dans le contexte qu'on lui passe
// en l'occurence 'this'.
// Appelle de n'importe quelle fonction parente
var Foo = function ( ) { };
Foo.prototype.hello = function ( ) { return 42; };
var F = function ( ) { };
F.prototype = Foo.prototype;
var Bar = function ( ) { };
Bar.prototype = new F( );
Bar.prototype.hello = function ( ) { return Foo.prototype.hello.call( this ) * 2; };
// On accède à la fonction 'hello' dans Foo.prototype, et on l'appelle en lui passant
// 'this' comme contexte.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment