JavaScript 继承详解(四)

所属分类: 网络编程 / JavaScript 阅读数: 1186
收藏 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。
更多精彩内容其他人还在看

深入解析Vue 组件命名那些事

本篇文章主要介绍了深入解析Vue 组件命名那些事,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Vue学习笔记进阶篇之vue-cli安装及介绍

这篇文章主要介绍了Vue学习笔记进阶篇之vue-cli安装及介绍,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

jquery版轮播图效果和extend扩展

这篇文章主要为大家详细介绍了jquery版轮播图效果,以及extend扩展的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

jQuery Validate格式验证功能实例代码(包括重名验证)

本文通过实例代码给大家介绍了jQuery Validate格式验证功能,代码中包括重名验证的方法,需要的的朋友参考下吧
收藏 0 赞 0 分享

Angular.js中angular-ui-router的简单实践

本篇文章主要介绍了Angular.js中angular-ui-router的简单实践,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

JavaScript实现二维坐标点排序效果

这篇文章主要为大家详细介绍了JavaScript实现二维坐标点排序效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

深入理解vue2.0路由如何配置问题

本篇文章主要介绍了vue2.0路由配置问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

基于bootstrap实现多个下拉框同时搜索功能

这篇文章主要为大家详细介绍了基于bootstrap实现多个下拉框同时搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

JavaScript 值类型和引用类型的初次研究(推荐)

这篇文章主要介绍了JavaScript 值类型和引用类型的初次研究,需要的朋友可以参考下
收藏 0 赞 0 分享

利用jQuery异步上传文件的插件用法详解

这篇文章主要介绍了利用jQuery异步上传文件的插件用法详解,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多