分享

JavaScript 从类继承

 WindySky 2009-07-02
关键字: javascript设计模式

从类继承

到这里,我们已经了解了构造函数和原型对象如何使您在JavaScript中模拟类。您可以看到,原型链可以确保所有对象都有Object.prototype的公用方法,以及如何使用闭包来模拟类的私有成员。但这里还缺少点什么。您尚未看到如何从类派生,这在C#中是每天必做的工作。遗憾的是,在JavaScript中从类继承并非像在C#中键入冒号即可继承那样简单,它需要进行更多操作。另一方面,JavaScript非常灵活,可以有很多从类继承的方式。

例如,有一个积累Pet,它有一个派生类Dog,如图9所示。这个在JavaScript中如何实现呢?Pet类很容易。您已经看见如何实现它了:


Js代码 复制代码
  1. // class Pet   
  2. function Pet(name)   
  3. {   
  4.         this.getName = function()   
  5.         {   
  6.                return name;   
  7.         }   
  8.         this.setName = function(newName)   
  9.         {   
  10.                name = newName;   
  11.         }   
  12. }   
  13.   
  14. Pet.prototype.toString = function()   
  15. {   
  16.         return "This pet's name is: " + this.getName();   
  17. }   
  18. // end of class Pet   
  19.   
  20. var parrotty = new Pet("Parrotty the Parrot");   
  21. alert(parrotty);  

 现在,如何创建从Pet派生的类Dog呢?在图9种可以看到,Dog有另一个属性breed,它改写了Pet的toString方法(注意,JavaScript的约定是方法和属性的名称使用camel大小写,而不是在C#中建议的Pascal大小写)。图10显示如何这样做。

 

Figure 10 从 Pet 类派生

Js代码 复制代码
  1. // class Dog : Pet   
  2. // public Dog(String name, String breed)   
  3. function Dog(name, breed)   
  4. {   
  5.         // think Dog: base(name)   
  6.         Pet.call(this, name);   
  7.         this.getBreed = function()   
  8.         {   
  9.                 return breed;   
  10.         }   
  11.            
  12.         // Breed doesn't change, obviously! It's read only.   
  13.         // this.setBreed = function(newBreed){breed = newBreed;}   
  14. }   
  15.   
  16. // this makes Dog.prototype inherits from Pet.prototype   
  17. Dog.prototype = new Pet();   
  18.   
  19. // remember that Pet.prototype.constructor   
  20. // point to Pet. We want out Dog instances' constructor   
  21. // to point to Dog.   
  22. Dog.prototype.constructor = Dog;   
  23.   
  24. // Now we override Pet.prototype.toString   
  25. Dog.prototype.toString = function()   
  26. {   
  27.         return "This dog's name is: " + this.getName() + " , and its breed " +   
  28.         "is: " + this.getBreed();   
  29. };   
  30. //end of class Dog   
  31.   
  32. var dog = new Dog("Buddy""Greed Dane");   
  33. // test the new toStirng()   
  34. alert(dog);   
  35.   
  36. // Testing instanceof (similar to the is operator)   
  37. // (dog is Dog)? yes   
  38. alert(dog instanceof Dog);   
  39. // (dog is Pet)? yes   
  40. alert(dog instanceof Pet);   
  41. // (dog is Object)? yes   
  42. alert(dog instanceof Object);  

 所使用的原型 — 替换技巧正确设置了原型链,因此假如使用C#,测试的实例将按预期运行。而且特权方法仍然会按预期运行。

下一节:模拟命名空间

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多