面向对象

面向对象思想的几个重要特征(针对类的要求):

抽象-封装、信息隐藏(将内部实现的方法和数据隐藏, 定义开放的接口)

继承-子类可以使用父类的资源,并可以定制自己的资源, 资源包括方法和数据

多态-重载(同名函数)、覆盖(继承的基础上重写父类函数)

JS与面向对象

javascript使用prototype实现类的继承功能, 非经典面向对象语言的类的形式, 使用方法也不同, 导致使用较困难。

请参考大师的《深入理解javascript原型和闭包系列http://www.cnblogs.com/wangfupeng1988/p/4001284.html

于是各种库都提供了自己实现类库, 例如:

1、 jquery class create: https://github.com/protonet/jquery-class-create

使用Class.Create创建实用类, 即实例的构造函数, 其缺点是用来jquery库

// properties are directly passed to `create` method
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
}); // when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
// redefine the speak method
say: function($super, message) {
return $super(message) + ', yarr!';
}
}); var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

2、 prototypejs :  http://prototypejs.org/learn/class-inheritance

作为prototypejs库的一个功能提供, 使用上跟jquery class create接口一致。

此库还提供, ajax和DOM优雅的接口, 消灭客户端开发的复杂性。

这两个库 要么依赖其他库, 要么自身库功能繁杂, 体积都大, 故单独使用的需求不满足。

本文介绍一个不依赖任何库、且实现上只包括类继承的库,  这位大神开发的独立库: John Resig http://ejohn.org/

Simple JavaScript Inheritance

Simple JavaScript Inheritance

此库的官网为

http://ejohn.org/blog/simple-javascript-inheritance/

作者的目标是 简单-容易被人理解, 可重用-不依赖其他库, 使用例子:

    var Person = Class.extend({

      init: function(isDancing){

        this.dancing = isDancing;

      },

      dance: function(){

        return this.dancing;

      }

    });

    var Ninja = Person.extend({

      init: function(){

        this._super( false );

      },

      dance: function(){

        // Call the inherited version of dance()

        return this._super();

      },

      swingSword: function(){

        return true;

      }

    });

    var p = new Person(true);

    p.dance(); // => true

    var n = new Ninja();

    n.dance(); // => false

    n.swingSword(); // => true

    // Should all be true

    p instanceof Person && p instanceof Class &&

    n instanceof Ninja && n instanceof Person && n instanceof Class

实现说明:

1、 创建构造函数必须简单, 构造函数只提供 init初始化方法。

2、 创建新类,必须扩展一个存在的类, 调用extend。

3、 所有的继承与唯一的祖先 Class。 创建的新类必须是Class的子类。

4、 子类中访问父类的同名方法(即被覆盖)必须提供。 通过this.super子类同名方法中调用父类同名方法。

实现要点

实现代码:

    /* Simple JavaScript Inheritance

    * By John Resig http://ejohn.org/

    * MIT Licensed.

    */

    // Inspired by base2 and Prototype

    (function(){

      var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

      // The base Class implementation (does nothing)

      this.Class = function(){};

      // Create a new Class that inherits from this class

      Class.extend = function(prop) {

        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,

        // don't run the init constructor)

        initializing = true;

        var prototype = new this();

        initializing = false;

        // Copy the properties over onto the new prototype

        for (var name in prop) {

          // Check if we're overwriting an existing function

          prototype[name] = typeof prop[name] == "function" &&

            typeof _super[name] == "function" && fnTest.test(prop[name]) ?

            (function(name, fn){

              return function() {

                var tmp = this._super;

                // Add a new ._super() method that is the same method

                // but on the super-class

                this._super = _super[name];

                // The method only need to be bound temporarily, so we

                // remove it when we're done executing

                var ret = fn.apply(this, arguments);       

                this._super = tmp;

                return ret;

              };

            })(name, prop[name]) :

            prop[name];

        }

        // The dummy class constructor

        function Class() {

          // All construction is actually done in the init method

          if ( !initializing && this.init )

            this.init.apply(this, arguments);

        }

        // Populate our constructed prototype object

        Class.prototype = prototype;

        // Enforce the constructor to be what we expect

        Class.prototype.constructor = Class;

        // And make this class extendable

        Class.extend = arguments.callee;

        return Class;

      };

    })();

要点:

1、初始化调用 xx.extend{init:function(){}} 中的 init执行初始化

    // The dummy class constructor

    function Class() {

      // All construction is actually done in the init method

      if ( !initializing && this.init )

        this.init.apply(this, arguments);

    }

2、 子类通过 this._super 访问父类的同名函数, 例如:

    var Person = Class.extend({

      init: function(isDancing){

        this.dancing = isDancing;

      }

    });

    var Ninja = Person.extend({

      init: function(){

        this._super( false );

      }

    });

    var p = new Person(true);

    p.dancing; // => true

    var n = new Ninja();

    n.dancing; // => false

如下, 将儿子有此函数, 父亲也有此同名函数时候, 此函数中记录函数地址到this._super中。

      // Check if we're overwriting an existing function

      prototype[name] = typeof prop[name] == "function" &&

        typeof _super[name] == "function" && fnTest.test(prop[name]) ?

        (function(name, fn){

          return function() {

            var tmp = this._super;

            // Add a new ._super() method that is the same method

            // but on the super-class

            this._super = _super[name];

            // The method only need to be bound temporarily, so we

            // remove it when we're done executing

            var ret = fn.apply(this, arguments);       

            this._super = tmp;

            return ret;

          };

        })(name, prop[name]) :

        prop[name];

    }

Simple JavaScript Inheritance--一个极简JS面向对象-类库的更多相关文章

  1. Vue.js 入门:从零开始做一个极简 To-Do 应用

    Vue.js 入门:从零开始做一个极简 To-Do 应用 写作时间:2019-12-10版本信息:Vue.js 2.6.10官网文档:https://cn.vuejs.org/ 前言  学习 Vue ...

  2. Spring Boot(5)一个极简且完整的后台框架

    https://blog.csdn.net/daleiwang/article/details/75007588 Spring Boot(5)一个极简且完整的后台框架 2017年07月12日 11:3 ...

  3. Join Resig's “Simple JavaScript Inheritance ”

    ======================Enein翻译=========================           John Resig 写了一篇关于 JavaScript 里类似其它语 ...

  4. 借助腾讯云的云函数实现一个极简的API网关

    借助腾讯云的云函数实现一个极简的API网关 Intro 微信小程序的域名需要备案,但是没有大陆的服务器,而且觉得备案有些繁琐,起初做的小程序都有点想要放弃了,后来了解到腾讯云的云函数,于是利用腾讯云的 ...

  5. RELabel : 一个极简的正则表达式匹配和展示框架

    html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,bi ...

  6. Simple JavaScript Inheritance(John Resig)

    I’ve been doing a lot of work, lately, with JavaScript inheritance – namely for my work-in-progress ...

  7. Simple JavaScript Inheritance

    1. [代码]Simple JavaScript Inheritance     (function(){  var initializing = false, fnTest = /xyz/.test ...

  8. 我喜欢的两个js类实现方式 现在再加上一个 极简主义法

    闭包实现 变量是不会变的:) var myApplication = function(){ var name = 'Yuri'; var age = '34'; var status = 'sing ...

  9. 【转】手摸手,带你用vue撸后台 系列四(vueAdmin 一个极简的后台基础模板)

    前言 做这个 vueAdmin-template 的主要原因是: vue-element-admin 这个项目的初衷是一个vue的管理后台集成方案,把平时用到的一些组件或者经验分享给大家,同时它也在不 ...

随机推荐

  1. iOS 自动布局小结

    1> sizeclasses 可以限制某个 storyboard 显示在什么样的屏幕上,如 当前 storyboard 在iPhone 的左斜右斜或 iPad上是否显示.. 2> Hug值 ...

  2. POJ 1321 简单dfs

    1.POJ 1321  棋盘问题 2.总结: 题意:给定棋盘上放k个棋子,要求同行同列都不重. #include<iostream> #include<cstring> #in ...

  3. HDU 1520 树形dp裸题

    1.HDU 1520  Anniversary party 2.总结:第一道树形dp,有点纠结 题意:公司聚会,员工与直接上司不能同时来,求最大权值和 #include<iostream> ...

  4. 深入浅出 - Android系统移植与平台开发(六)- 为Android启动加速

    作者:唐老师,华清远见嵌入式学院讲师. Android的启动速度一直以来是他的诟病,虽然现在Android设备的硬件速度越来越快,但是随着新 版本的出现,其启动速度一直都比较慢,当然,作为程序员,我们 ...

  5. linux ps指令

    ps axjf <==連同部分程序樹狀態

  6. JS相关环境搭建:Nodejs、karma测试框架、jsDuck、Express

    第一章:压缩js(nodejs,uglify) 第一步:安装nodejs环境 直接下载http://www.nodejs.org/download/ 下载完成后直接下一步下一步即可,完了我们就具有no ...

  7. Func<T, TResult> Delegate

    public delegate TResult Func<in T, out TResult>( T arg ) http://msdn.microsoft.com/en-us/libra ...

  8. linux recv 返回值与linux socket 错误分析

    转载:http://blog.csdn.net/henry115/article/details/7054603 recv函数 int recv( SOCKET s, char FAR *buf, i ...

  9. 【android tools】内存、网络、界面性能响应优化的工具

    一.性能优化工具 性能分析,我理解有内存性能,IO性能, 界面性能,耗电等. 内存性能,用debuggable的app结合mat等专业工具可以分析.另外最近的Leakcanary很好用,但是要手动加入 ...

  10. MUI - DIV窗体切换

    神坑记录: 1.js报错异常:没有找到"innerHeight"属性? 解决方案:暂时不知原因,通过对mui.view.js进行调试得知是跳转目标页没有 .mui-navbar-l ...