JavaScript Patterns 6.3 Klass

Commonalities

• There’s a convention on how to name a method, which is to be considered the constructor of the class.

• Classes inherit from other classes.

• There’s access to the parent class (superclass) from within the child class.

The function takes two parameters: a parent class to be inherited and implementation of the new class provided by an object literal.

1. A  Child()  constructor function is created. This is the function that will be returned at the end and will be used as a class. In this function the __construct method is called if it exists. Also before that the parent’s  __construct is called (again, if it exists)  using  the  static  uber property.  There  might  be  cases  when uber is  not defined—when  you  inherit  from  Object for  example,  as  the  case  was  with  the Man class definition.

2. The second part takes care of the inheritance bit. It’s simply using the classical inheritance’s Holy Grail pattern. There’s only one new thing: setting the Parent to Object if no  Parent was passed to inherit from.

3. The  final  section  is  looping  through  all  the  implementation  methods  (such  as __construct and getNam ein the examples), which are the actual definition of the class and adding them to the prototype of Child.

var klass = function (Parent, props) {

    var Child, F, i;

    // 1. new constructor

    Child = function () {

        if (Child.uber && Child.uber.hasOwnProperty("__construct")) {

            Child.uber.__construct.apply(this, arguments);

        }

        if (Child.prototype.hasOwnProperty("__construct")) {

            Child.prototype.__construct.apply(this, arguments);

        }

    };

    // 2. inherit

    Parent = Parent || Object;

    F = function () {};

    F.prototype = Parent.prototype;

    Child.prototype = new F();

    Child.uber = Parent.prototype;

    Child.prototype.constructor = Child;

    // 3. add implementation methods

    for (i in props) {

        if (props.hasOwnProperty(i)) {

            Child.prototype[i] = props[i];

        }

    }

    // return the "class"

    return Child;

};

// The demo for the 6.2 Klass

var Man = klass(null, {

    __construct: function (what) {

        showMsg("Man‘s constructor");

        this.name = what;

    },

    getName: function () {

        return this.name;

    }

});

var SuperMan = klass(Man, {

    __construct: function (what) {

        showMsg("SuperMan‘s constructor");

    },

    getName: function () {

        var name;

        if (SuperMan.uber.hasOwnProperty("getName")) {

            name = SuperMan.uber.getName.call(this);

        }

        return "I am " + name;

    }

});

function showMsg(msg) {

    $(‘#msg‘).append(msg).append(‘<br/>‘);

}

$(function () {

    var clark = new SuperMan(‘Clark Kent‘);

    showMsg(clark.getName());

    // "I am Clark Kent"

});

Advantage

This pattern allows you to forget about the prototypes completely, and the good thing is you can tweak the syntax and the conventions

to resemble another of your favorite languages.

Disadvantage

It brings the whole confusing notion of classes, which don’t technically exist in the language. It adds new syntax and new rules to learn and remember.

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 6.3 Klass,布布扣,bubuko.com

时间: 2024-10-06 05:35:26

JavaScript Patterns 6.3 Klass的相关文章

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"  One reason

JavaScript Patterns 2 Essentials - Writing Maintainable Code

Revisiting the code after some time has passed requires: ? Time to relearn and understand the problem ? Time to understand the code that is supposed to solve the problem As the application matures, many other things happen that require your code to b

JavaScript Patterns 7.1 Singleton

7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =

JavaScript Patterns 2.12 Writing API Docs

Free and open source tools for doc generation: the JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/) and YUIDoc (http://yuilibrary.com/projects/yuidoc). Process of generating API documentation ? Writing specially formatted code blocks ? Running

JavaScript Patterns 2.11 Writing Comments

Document all functions, their arguments and return values, and also any interesting or unusual algorithm or technique. Think of the comments as hints to the future readers of the code; the readers need to understand what your code does without readin

JavaScript Patterns 2.2 - Minimizing Globals

Access a global variable in a browser environment: myglobal = "hello"; // antipattern console.log(myglobal); // "hello" console.log(window.myglobal); // "hello" console.log(window["myglobal"]); // "hello"

JavaScript Patterns 4.7 Init-Time Branching

When you know that a certain condition will not change throughout the life of the program, it makes sense to test the condition only once. Browser sniffing (or feature detection) is a typical example. // BEFORE var utils = { addListener : function(el

JavaScript Patterns 3.6 Regular Expression Literal

1. Using the new RegExp() constructor // constructor var re = new RegExp("\\\\", "gm"); 2. Using the regular expression literal // regular expression literal var re = /\\/gm;  when using the RegExp()constructor, you also need to escape