JavaScript OOP练习第一弹(1 位领导批示)

学javascript已经有一段时间了,成天与DOM,文档对像打交道,水平停滞不前.今天来进阶练习,学习 javascript OOP 写了一点简单的代码

  1. <script type="text/javascript">
  2. /*定义宠物对像*/
  3. function Pet()
  4. {
  5.     //名称
  6.     this.name = null;
  7.     //毛色
  8.     this.color = null;
  9.     //设置名称
  10.     this.setName = function(newName)
  11.     {
  12.         this.name = newName;
  13.     };
  14.     //获取名称
  15.     this.getName = function()
  16.     {
  17.         return this.name;
  18.     };
  19.     //获取颜色
  20.     this.getColor = function()
  21.     {
  22.         return this.color;
  23.     };
  24.     //设置颜色
  25.     this.setColor = function(newColor)
  26.     {
  27.         this.color = newColor;
  28.     };
  29.     //定义一个要实现的方法
  30.     this.getFood = null;
  31.     //获取宠物对像的描述信息
  32.     this.showPet = function()
  33.     {
  34.         return this.color + "色的" + this.name + "最喜欢吃的食物是" + this.getFood();
  35.     }
  36. }
  37.  
  38. //定义狗狗对像
  39. function Dog() {
  40.     this.getFood = function()
  41.     {
  42.         return "骨头";
  43.     };
  44. }
  45.  
  46. //声明Dog的原型
  47. Dog.prototype = new Pet();
  48. </script>
  49.  
  50. <script type="text/javascript">
  51. //实例化一只名叫koko的黄色小狗
  52. var mydog = new Dog();
  53. //设置koko的属性
  54. mydog.setName("koko");
  55. mydog.setColor("");
  56. //输出测试
  57. alert(mydog.showPet());
  58. </script>

第一次学习练习,难免浅显.见笑

相关文章

分享到新浪微博 推荐到豆瓣 分享到 Google Reader 加入Google书签 嘀咕一下 分享到饭否 分享到做啥 分享到叽歪 分享到鲜果 加入QQ书签 加入百度搜藏 加入雅虎书签 分享到垦一垦

  1. 1
    tour

    编程真TM地不爽~

请领导指示

验证码 (必须)

Additional comments powered by BackType

随机显示的10篇日志

评论最多的10篇日志

浏览最多的10篇日志