Function.prototype.constitute >= 0.1.4

Purpose

Do things to the class constructor once it's ready, and inherit to children

Description

Sometimes you want to do something to a class every time it's inherited. This lets you do that.

It is not called, for example, `Function#inherited` because it also applies to the parent class.

Syntax

Function#constitute ( Functiontask );

Parameters

task

The function to perform

Return values

Examples

Create a parent and a child class and use constitutors

First we have to create the classes

// First create the base class
var Base = Function.inherits(function Base() {});

// And add a constitutor
Base.constitute(function myConstitutorFunction() {
    // `this` refers to the current class (constructor)
    this.setProperty('pretty_name', this.name.before('Base') || this.name);
});

// Create a new class
var Child = Function.inherits('Base', function ChildBase() {});

Constitutors are not called on instance creation, but on class creation. They do happen asynchronously, though.

Protoblast.nextTick(function doWhenLoaded() {
    // Now create an instance of the Base class
    var base = new Base();
    
    // It'll have a prototypal property `pretty_name` with value "Base"
    console.log(base.pretty_name);
    >>> 'Base';
    
    // Create an instance of the Child class
    var child = new Child();
    
    // It'll also have that property, but with another value
    console.log(child.pretty_name);
    >>> 'Child';
});

Comments

Roel Van Gils

Very nice!

Chloe

I located your website from Google and I have to say it was an excellent locate. Thanks!

Shayna

Do you have any kind of tips for creating articles? That's where I constantly battle as well as I simply wind up gazing vacant screen for very long time.