当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 继承详解(四)

Javascript
一个短小精悍使用的对象化QQ菜单
用数据岛生成翻页程序
轻松实现删除确认
IE5中用JavaScript跨frame加option问题
IE6无提示关闭窗口,不是利用activeX
下拉框联动
用dhtml做了一个密码管理器
面向对象的JavaScript编程
网 络 病 毒 与 防 范 措 施
破解网页禁止鼠标右键的技巧
JS编写的俄罗斯方块
通过代码改变客户端所显示的语言类型
欢迎精灵
事件处理函数OnEnter OnExit 使用一例
称三次从12球中找出唯一但不知轻重的球
VML实现的饼图(JavaScript类封装)
搜索gb2312汉字在网上的频率
真正的 用JS 做的 loading
Vml:应用阿基米德算法在网页制作动画,原程+注释
贴一例:当所有图片下载完毕时,然后显示网页(有进度)

Javascript 中的 JavaScript 继承详解(四)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 206 ::
收藏到网摘: n/a

在本章中,我们将分析Douglas Crockford关于JavaScript继承的一个实现 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。