JavaScript 继承详解(四)

所属分类: 网络编程 / JavaScript 阅读数: 1169
收藏 0 赞 0 分享
Classical Inheritance in JavaScript
Crockford是JavaScript开发社区最知名的权威,是JSONJSLintJSMinADSafe之父,是《JavaScript: The Good Parts》的作者。
现在是Yahoo的资深JavaScript架构师,参与YUI的设计开发。 这里有一篇文章详细介绍了Crockford的生平和著作。
当然Crockford也是我等小辈崇拜的对象。

调用方式

首先让我们看下使用Crockford式继承的调用方式:
注意:代码中的method、inherits、uber都是自定义的对象,我们会在后面的代码分析中详解。

    // 定义Person类
    function Person(name) {
      this.name = name;
    }
    // 定义Person的原型方法
    Person.method("getName", function() {
      return this.name;
    }); 
    
    // 定义Employee类
    function Employee(name, employeeID) {
      this.name = name;
      this.employeeID = employeeID;
    }
    // 指定Employee类从Person类继承
    Employee.inherits(Person);
    // 定义Employee的原型方法
    Employee.method("getEmployeeID", function() {
      return this.employeeID;
    });
    Employee.method("getName", function() {
      // 注意,可以在子类中调用父类的原型方法
      return "Employee name: " + this.uber("getName");
    });
    // 实例化子类
    var zhang = new Employee("ZhangSan", "1234");
    console.log(zhang.getName());  // "Employee name: ZhangSan"
    

 

这里面有几处不得不提的硬伤:

  • 子类从父类继承的代码必须在子类和父类都定义好之后进行,并且必须在子类原型方法定义之前进行。
  • 虽然子类方法体中可以调用父类的方法,但是子类的构造函数无法调用父类的构造函数。
  • 代码的书写不够优雅,比如原型方法的定义以及调用父类的方法(不直观)。

 

当然Crockford的实现还支持子类中的方法调用带参数的父类方法,如下例子:

    function Person(name) {
      this.name = name;
    }
    Person.method("getName", function(prefix) {
      return prefix + this.name;
    });

    function Employee(name, employeeID) {
      this.name = name;
      this.employeeID = employeeID;
    }
    Employee.inherits(Person);
    Employee.method("getName", function() {
      // 注意,uber的第一个参数是要调用父类的函数名称,后面的参数都是此函数的参数
      // 个人觉得这样方式不如这样调用来的直观:this.uber("Employee name: ")
      return this.uber("getName", "Employee name: ");
    });
    var zhang = new Employee("ZhangSan", "1234");
    console.log(zhang.getName());  // "Employee name: ZhangSan"
    

 

代码分析

首先method函数的定义就很简单了:

    Function.prototype.method = function(name, func) {
      // this指向当前函数,也即是typeof(this) === "function"
      this.prototype[name] = func;
      return this;
    };
    
要特别注意这里this的指向。当我们看到this时,不能仅仅关注于当前函数,而应该想到当前函数的调用方式。 比如这个例子中的method我们不会通过new的方式调用,所以method中的this指向的是当前函数。

 

inherits函数的定义有点复杂:

    Function.method('inherits', function (parent) {
      // 关键是这一段:this.prototype = new parent(),这里实现了原型的引用
      var d = {}, p = (this.prototype = new parent());
      
      // 只为子类的原型增加uber方法,这里的Closure是为了在调用uber函数时知道当前类的父类的原型(也即是变量 - v)
      this.method('uber', function uber(name) {
        // 这里考虑到如果name是存在于Object.prototype中的函数名的情况
        // 比如 "toString" in {} === true
        if (!(name in d)) {
          // 通过d[name]计数,不理解具体的含义
          d[name] = 0;
        }    
        var f, r, t = d[name], v = parent.prototype;
        if (t) {
          while (t) {
            v = v.constructor.prototype;
            t -= 1;
          }
          f = v[name];
        } else {
          // 个人觉得这段代码有点繁琐,既然uber的含义就是父类的函数,那么f直接指向v[name]就可以了
          f = p[name];
          if (f == this[name]) {
            f = v[name];
          }
        }
        d[name] += 1;
        // 执行父类中的函数name,但是函数中this指向当前对象
        // 同时注意使用Array.prototype.slice.apply的方式对arguments进行截断(因为arguments不是标准的数组,没有slice方法)
        r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
        d[name] -= 1;
        return r;
      });
      return this;
    });
    
注意,在inherits函数中还有一个小小的BUG,那就是没有重定义constructor的指向,所以会发生如下的错误:
    var zhang = new Employee("ZhangSan", "1234");
    console.log(zhang.getName());  // "Employee name: ZhangSan"
    console.log(zhang.constructor === Employee);  // false
    console.log(zhang.constructor === Person);   // true
    

 

改进建议

根据前面的分析,个人觉得method函数必要性不大,反而容易混淆视线。 而inherits方法可以做一些瘦身(因为Crockford可能考虑更多的情况,原文中介绍了好几种使用inherits的方式,而我们只关注其中的一种), 并修正了constructor的指向错误。

    Function.prototype.inherits = function(parent) {
      this.prototype = new parent();
      this.prototype.constructor = this;
      this.prototype.uber = function(name) {
        f = parent.prototype[name];
        return f.apply(this, Array.prototype.slice.call(arguments, 1));
      };
    };
    
调用方式:
    function Person(name) {
      this.name = name;
    }
    Person.prototype.getName = function(prefix) {
      return prefix + this.name;
    };
    function Employee(name, employeeID) {
      this.name = name;
      this.employeeID = employeeID;
    }
    Employee.inherits(Person);
    Employee.prototype.getName = function() {
      return this.uber("getName", "Employee name: ");
    };
    var zhang = new Employee("ZhangSan", "1234");
    console.log(zhang.getName());  // "Employee name: ZhangSan"
    console.log(zhang.constructor === Employee);  // true
    

 

有点意思

在文章的结尾,Crockford居然放出了这样的话:

I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.
可见Crockford对在JavaScript中实现面向对象的编程不赞成,并且声称JavaScript应该按照原型和函数的模式(the prototypal and functional patterns)进行编程。
不过就我个人而言,在复杂的场景中如果有面向对象的机制会方便的多。
但谁有能担保呢,即使像jQuery UI这样的项目也没用到继承,而另一方面,像Extjs、Qooxdoo则极力倡导一种面向对象的JavaScript。 甚至Cappuccino项目还发明一种Objective-J语言来实践面向对象的JavaScript。
更多精彩内容其他人还在看

纯javascript判断查询日期是否为有效日期

很多网站都涉及到输入日期选项,如果客户日期输入错误,可能导入查询不到甚至查询到错误的信息,为了更好的满足用户需求,需要对日期进行校验,下面给大家介绍使用纯javascript如何判断查询日期是否为有效日期,需要的朋友可以参考下
收藏 0 赞 0 分享

jquery实现的蓝色二级导航条效果代码

这篇文章主要介绍了jquery实现的蓝色二级导航条效果代码,涉及jquery鼠标事件及页面样式的动态切换效果实现技巧,非常简单实用,需要的朋友可以参考下
收藏 0 赞 0 分享

ajax如何实现页面局部跳转与结果返回

AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术,通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新,本篇文章给大家介绍ajax如何实现页面局部跳转与结果返
收藏 0 赞 0 分享

jQuery实现的类似淘宝网站搜索框样式代码分享

这篇文章主要介绍了类似淘宝网站搜索框样式实现代码,推荐给大家,有需要的小伙伴可以参考下。
收藏 0 赞 0 分享

js实现的黑背景灰色二级导航菜单效果代码

这篇文章主要介绍了js实现的黑背景灰色二级导航菜单效果代码,涉及javascript操作页面元素动态切换的实现技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

jQuery仿360导航页图标拖动排序效果代码分享

这篇文章主要为大家详细介绍了360导航页图标拖动排序效果代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

javascript中SetInterval与setTimeout的定时器用法

Javascript的setTimeOut和setInterval函数应用非常广泛,它们都用来处理延时和定时任务,比如打开网页一段时间后弹出一个登录框,页面每隔一段时间发送异步请求获取最新数据等,本文文章通过代码示例给大家介绍javascript中SetInterval与setT
收藏 0 赞 0 分享

jquery带下拉菜单和焦点图代码分享

这篇文章主要介绍了jquery带下拉菜单和焦点图代码,推荐给大家,有需要的小伙伴可以参考下。
收藏 0 赞 0 分享

jQuery实现的背景动态变化导航菜单效果

这篇文章主要介绍了jQuery实现的背景动态变化导航菜单效果,涉及jquery页面元素背景动态变换的实现技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

jquery+CSS实现的水平布局多级网页菜单效果

这篇文章主要介绍了jquery+CSS实现的水平布局多级网页菜单效果,涉及jquery页面元素属性动态变换效果实现技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多