• 使用JavaScript中的call,apply构建一个基础的继承类


    网上看到的,当做学习call,apply的一个案例,

     1 var b = {};//base
     2 var slice = [].slice;
     3 
     4 b.Class = function (supClass, childAttr) {
     5     //若是传了第一个类,便继承之;否则实现新类
     6     if (typeof supClass === 'object') {
     7         childAttr = supClass;
     8         supClass = function () { };
     9     }
    10 
    11     //定义我们创建的类
    12     var newClass = function () {
    13         this._properties_();
    14         this.init.apply(this, arguments);
    15     };
    16     newClass.prototype = new supClass();
    17 
    18     var supInit = newClass.prototype.init || function () { };
    19     var childInit = childAttr.init || function () { };
    20     var _supAttr = newClass.prototype._properties_ || function () { };
    21     var _childAttr = childAttr._properties_ || function () { };
    22 
    23     for (var k in childAttr) {
    24         //_properties_中作为私有属性
    25         childAttr.hasOwnProperty(k) && (newClass.prototype[k] = childAttr[k]);
    26     }
    27 
    28     //继承的属性有可能重写init方法
    29     if (arguments.length && arguments[0].prototype && arguments[0].prototype.init === supInit) {
    30         //重写新建类,初始化方法,传入其继承类的init方法
    31         newClass.prototype.init = function () {
    32             var scope = this;
    33             var args = [function () {
    34                 supInit.apply(scope, arguments);
    35             } ];
    36             childInit.apply(scope, args.concat(slice.call(arguments)));
    37         };
    38     }
    39 
    40     //内部属性赋值
    41     newClass.prototype._properties_ = function () {
    42         _supAttr.call(this);
    43         _childAttr.call(this);
    44     };
    45 
    46     //成员属性
    47     for (var k in supClass) {
    48         supClass.hasOwnProperty(k) && (newClass[k] = supClass[k]);
    49     }
    50     return newClass;
    51 };

    原文地址:http://www.cnblogs.com/yexiaochai/p/3236544.html

  • 相关阅读:
    视频监控中运动物体检测与跟踪----相邻帧差法和三帧差法
    辨异 —— 近义词(词组)
    H264 编解码框架简单介绍
    一个build.xml实例
    SQL server 错误代码对比表
    怎样使用oracle 的DBMS_SQLTUNE package 来执行 Sql Tuning Advisor 进行sql 自己主动调优
    Android中ExpandableListView控件基本使用
    c++中sort()及qsort()的使用方法总结
    Oracle动态SQL语句
    Oracle Minus 取差集
  • 原文地址:https://www.cnblogs.com/sere/p/5124547.html
Copyright © 2020-2023  润新知