Class.create Vs Object.extend

Prototype在1.6之前的实现一个继承的操作的时候都是采用Object.extend的方式。Object.extend的实现原理是先创建出父类的对象并将子类中的方法复制到这个对象中去,这样做可以比较轻松的实现一个子类到父类的upcasting。但是这样也会存在一个问题,就是子类无法在自己的构造函数中调用父类的构造函数,也就是说无法实现super这样的操作。

1.6以前的Object.extend的实现代码:

  
  1. Object. extend = function (destination, source ) {
  2. for ( var property in source ) {
  3. destination [property ] = source [property ];
  4. }
  5. return destination;
  6. }

1.6的Prototype中改写了关于继承的实现,Class.create新增加了一种模式的调用,Class.create([BassClass], {});

Prototypejs.org提供的Class.create新的实例:

  
  1. var Animal = Class. create ( {
  2. initialize: function ( name, sound ) {
  3. this. name = name;
  4. this. sound = sound;
  5. },
  6.  
  7. speak: function ( ) {
  8. alert ( this. name + " says: " + this. sound + "!" );
  9. }
  10. } );
  11.  
  12. // subclassing Animal
  13. var Snake = Class. create (Animal, {
  14. initialize: function ($super, name ) {
  15. $super ( name, 'hissssssssss' );
  16. }
  17. } );
  18.  
  19. var ringneck = new Snake ( "Ringneck", "hissssssss" );
  20. ringneck. speak ( );
  21.  
  22. //-> alerts "Ringneck says: hissssssss!"
  23.  

在这个实例中我们看到了$super这个新增加的函数,通过$super方法我们可以调用父类的方法。再来看一下最新的Prototype 1.6中的Class.create的实现:

  
  1. /* Based on Alex Arnell's inheritance implementation. */
  2. var Class = {
  3. create: function ( ) {
  4. var parent = null, properties = $A (arguments );
  5. if (Object. isFunction (properties [ 0 ] ) )
  6. parent = properties. shift ( );
  7.  
  8. function klass ( ) {
  9. this. initialize. apply ( this, arguments );
  10. }
  11.  
  12. Object. extend (klass, Class. Methods );
  13. klass. superclass = parent;
  14. klass. subclasses = [ ];
  15.  
  16. if (parent ) {
  17. var subclass = function ( ) { };
  18. subclass. prototype = parent. prototype;
  19. klass. prototype = new subclass;
  20. parent. subclasses. push (klass );
  21. }
  22.  
  23. for ( var i = 0; i < properties. length; i++ )
  24. klass. addMethods (properties [i ] );
  25.  
  26. if (!klass. prototype. initialize )
  27. klass. prototype. initialize = Prototype. emptyFunction;
  28.  
  29. klass. prototype. constructor = klass;
  30.  
  31. return klass;
  32. }
  33. };

可以看到最新的继承实现将父类暂存中superclass,这样在子类中通过$super调用父类的方法时,实际上调用的是this.superclass中的方法。

在开发Glove.Widget时候曾经就为没有super方法犯愁过,现在1.6有了新的继承模式Glove.Widget就不用像以前那样丑陋的实现super的功能了。明天开始考虑Glove.Widget基于Prototype1.6的重构。

你可能感兴趣的:(prototype)