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的更多相关文章

  1. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  2. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  3. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  4. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  5. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  6. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  7. JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns

    In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...

  8. JavaScript Patterns 5.9 method() Method

    Advantage Avoid re-created instance method to this inside of the constructor. method() implementatio ...

  9. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

随机推荐

  1. echarts 折线图动态x轴及数据

    <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" ...

  2. Csharp: Create Excel Workbook or word from a Template File using aspose.Word 14.5 and aspose.Cell 8.1

    winform: /// <summary> /// /// </summary> /// <param name="sender"></ ...

  3. Java并发编程:并发容器之ConcurrentHashMap(转载)

    Java并发编程:并发容器之ConcurrentHashMap(转载) 下面这部分内容转载自: http://www.haogongju.net/art/2350374 JDK5中添加了新的concu ...

  4. python统计列表内元素个数

    代码如下: list01 = ['a','b','c','a','c'] set01 = set(list01) print(set01) dict01 = {} for item in set01: ...

  5. 大家一起撸代码之——Hibernate各种主键生成策略与配置详解

    1.assigned 主键由外部程序负责生成,在 save() 之前必须指定一个.Hibernate不负责维护主键生成.与Hibernate和底层数据库都无关,可以跨数据库.在存储对象前,必须要使用主 ...

  6. 【我的产品观】开发wangEditor一年总结

    1. 引言 标题说是一周年,其实是不是正好是一周年,我也忘记了,光从github的提交记录看也不准确.印象中觉得,如果要论想法,到现在一年多了,如果要论实际写代码,可能差不多正好一年. 从8月底在济南 ...

  7. 一款很实用的jQuery鼠标悬浮有动画效果的响应式瀑布流插件

    一款很实用的jQuery鼠标悬浮有动画效果的响应式瀑布流插件 在线预览 下载地址 实例代码 <!doctype html> <html lang="zh"> ...

  8. JavaScriptOO.com – 快速找到你需要的 JS 框架

    JavaScriptOO.com 集合了目前 Web 开发中最常用的422(截至目前)款 JavaScript 框架,你可以根据功能类别(Ajax,动画,图表,游戏等)进行过滤和排序,快速找到你需要的 ...

  9. ionic + cordova 使用 cordova-plugin-crosswalk-webview 中的一些个坑

    1) 在使用Web Audio API 时,无法使用 AudioContext.decodeAudioData() 对MP3文件进行解码 2)使用Cordova-plugin-weibosdk 插件时 ...

  10. npm 安装 ionic cordova

    针对npm安装 ionic 和 cordova 过程很慢,且有些安装文件被墙的问题,使用如下方式解决: 1)安装cnpm npm install -g cnpm 2)然后再使用cnpm 安装 ioni ...