JavaScript 继承详解(四)


Posted in Javascript onJuly 13, 2009

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 验证表单(form)中的单选(radio)值
Sep 08 Javascript
checkbox全选/取消全选以及checkbox遍历jQuery实现代码
Dec 02 Javascript
javascript 学习笔记(八)javascript对象
Apr 12 Javascript
jquery中change()用法实例分析
Feb 06 Javascript
Bootstrap每天必学之附加导航(Affix)插件
Apr 25 Javascript
jquery div模态窗口的简单实例
May 28 Javascript
AngularJS入门教程之模块化操作用法示例
Nov 02 Javascript
详解vue-cli 构建Vue项目遇到的坑
Aug 30 Javascript
jQuery+PHP实现上传裁剪图片
Jun 29 jQuery
js replace替换字符串同时替换多个方法
Nov 27 Javascript
AntV F2和vue-cli构建移动端可视化视图过程详解
Oct 08 Javascript
vue浏览器返回监听的具体步骤
Feb 03 Vue.js
JavaScript 继承详解(三)
Jul 13 #Javascript
JavaScript 继承详解(二)
Jul 13 #Javascript
JavaScript 继承详解(一)
Jul 13 #Javascript
javascript dom 操作详解 js加强
Jul 13 #Javascript
jquery 学习笔记 传智博客佟老师附详细注释
Sep 12 #Javascript
JavaScript 事件查询综合
Jul 13 #Javascript
JavaScript 事件对象的实现
Jul 13 #Javascript
You might like
PHP+AJAX实现无刷新注册(带用户名实时检测)
2007/01/02 PHP
php 将bmp图片转为jpg等其他任意格式的图片
2009/06/21 PHP
Godaddy空间Zend Optimizer升级方法
2010/05/10 PHP
PHP Warning: PHP Startup: Unable to load dynamic library \ D:/php5/ext/php_mysqli.dll\
2012/06/17 PHP
php.ini-dist 和 php.ini-recommended 的区别介绍(方便开发与安全的朋友)
2012/07/01 PHP
PHP采用自定义函数实现遍历目录下所有文件的方法
2014/08/19 PHP
ubuntu下配置nginx+php+mysql详解
2015/09/10 PHP
给WordPress中的留言加上楼层号的PHP代码实例
2015/12/14 PHP
PHP加密解密实例分析
2015/12/25 PHP
javascript eval函数深入认识
2009/02/21 Javascript
使用JQuery快速实现Tab的AJAX动态载入(实例讲解)
2013/12/11 Javascript
node.js 开发指南 ? Node.js 连接 MySQL 并进行数据库操作
2014/07/29 Javascript
原生js和jQuery写的网页选项卡特效对比
2015/04/27 Javascript
JavaScript判断手机号运营商是移动、联通、电信还是其他(代码简单)
2015/09/25 Javascript
jquery 校验中国身份证号码实例详解
2017/04/11 jQuery
JScript实现地址选择功能
2017/08/15 Javascript
Javascript中toFixed计算错误(依赖银行家舍入法的缺陷)解决方法
2017/08/22 Javascript
微信小程序和百度的语音识别接口详解
2019/05/06 Javascript
Vue编程式跳转的实例代码详解
2019/07/10 Javascript
layUI使用layer.open,在content打开数据表格,获取值并返回的方法
2019/09/26 Javascript
node读写Excel操作实例分析
2019/11/06 Javascript
详解js中的原型,原型对象,原型链
2020/07/16 Javascript
微信小程序onShareTimeline()实现分享朋友圈
2021/01/07 Javascript
分享一下Python 开发者节省时间的10个方法
2015/10/02 Python
Django模型序列化返回自然主键值示例代码
2019/06/12 Python
python GUI库图形界面开发之PyQt5单行文本框控件QLineEdit详细使用方法与实例
2020/02/27 Python
python读取文件指定行内容实例讲解
2020/03/02 Python
Python实现自动装机功能案例分析
2020/10/22 Python
python 基于opencv去除图片阴影
2021/01/26 Python
Nº21官方在线商店:numeroventuno.com
2019/09/26 全球购物
为什么需要版本控制
2016/10/28 面试题
冰淇淋店创业计划书范文
2013/12/27 职场文书
电信营业员自我评价分享
2014/01/17 职场文书
给老婆的婚前保证书
2014/02/01 职场文书
中药学专业求职信
2014/05/31 职场文书
2015年纪检监察工作总结
2015/04/08 职场文书