JavaScript是一种弱类型语言,缺乏类这样的定义(正在制订的JavaScript 2.0规范中已经引入)。JavaScript最基础也最有意思的一个设定就是prototype,基本来说,对于这门语言而言,摆平prototype基本也就算进入高级了——当然,浏览器部分另算。
JavaScript本身并不是一种包含面向对象理念的语言,在你跟浏览器搏斗的过程中往往也是用不着面向对象的,但如果你想做JS lib的话,使用OO的概念会让好些东西都容易得多。
增强JavaScript的面向对象特质,构建类的机制,可以在JavaScript中使用原型链继承(prototype chain)来实现这样的一种机制。
先来看看下面这段代码。
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | /*Revised from EXT JS*/ My.extend = function(/*superclass object, it is a function*/sp, /*configuration object*/c){ // Construct the subclass, it just calls the super class to execute the functionality. var sb = function(conf){ return sp.apply(this,arguments); }; // Blank new trivial function. var F = function(){}; F.prototype = sp.prototype; // Copy prototype. sb.prototype = new F(); sb.prototype.constructor = sb; // Add super class attribute to subclass in case you want to use parent method. sb.superclass = sp.prototype; // Add extended method of the subclass. My.apply(sb.prototype, c); return sb; }; |
上面这样的一种机制使得类继承很容易实现。而使用的时候,可以采用下面这一种方式。
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var My = {}; My.apply = function(o, c){ if (o && c) for (var m in c) o[m] = c[m]; }; // Set up My.a My.a = function(conf){ My.apply(this,conf); }; My.apply(My.a.prototype, { msg: 'default message', show:function(){ alert(this.msg); } }); // Extend My.b from My.a My.b = My.extend(My.a, { show:function(){ alert("extended " + this.msg); } }); var testA = new My.a(); var testB = new My.b(); testA.show(); // 'default message' testB.show(); // 'extended default message' |
在一些面向对象的JS框架中这个理念被广泛使用着,而其实JavaScript的OO理念早在2003年(或者更早?)的时候就已经被提出了。
你可以看一下Mike Koss的Object Oriented Programming in JavaScript。
23:03, 2009-08-30Chris /
怒顶技术帖!
09:28, 2009-08-31shen /
啊~~开眼界了~~果然是学无止境~~
13:23, 2009-08-31Justice /
浏览器兼容是民工活...这个才是大师做的事。
20:19, 2009-08-31hester /
很漂亮……的页面~
13:19, 2009-09-02Edward /
难得有博可以在公司上,路过。