In Part 1 we looked at basic class definitions using WinJS.Class and how this helper gives you a structure through which you can define classes without directly messing with object prototypes.

In this part we’ll look at the next piece in WinJS.Class, namely WinJS.Class.derive. As you’d expect, this method allows you to basically add instance and static members to an existing class. The syntax is:

WinJS.Class.derive(baseClass, constructor, instanceMembers, staticMembers);

where baseClass is the name of a class previously defined with WinJS.Class.define or WinJS.Class.derive, or, for that matter, really any other object. The other three parameters are the same as those of WinJS.Class.define, with the same meaning.

Peeking into the WinJS sources (base.js), we can see how derive works:

if (baseClass) {
    constructor = constructor || function () { };
    var basePrototype = baseClass.prototype;
constructor.prototype = Object.create(basePrototype);

    Object.defineProperty(constructor.prototype, “constructor”, { value: constructor, writable: true, configurable: true, enumerable: true });

    if (instanceMembers) {
        initializeProperties(constructor.prototype, instanceMembers);

    if (staticMembers) {
        initializeProperties(constructor, staticMembers);

    return constructor;
} else {
    return define(constructor, instanceMembers, staticMembers);

You can see that if baseClass is null, derive is just an alias for define, and if you indicate null for the constructor, an empty function is provided. Otherwise you can see that the derived class is given a copy of the base class’ prototype, so that the two won’t interfere with each other. After that, derive then adds the static and instance properties as did define.

Because baseClass already has its own instance and static members, they’re already present in its prototype, so those members carry over into the derived class, as you’d expect. But again, if you make later changes to members of that original baseClass, those changes only affect the derivation and not the original.

Looking around the rest of WinJS, you’ll see that derive is used in a variety of places to centralize implementation that’s shared between similar controls and data sources, for example.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>