javascript 基于原型的知识--如何实现继承[转]

javascript 是一种基于原型的语言,没有显示的继承符号,它有2种隐式的方式可以实现面向对象中的继承:
   1 .   在子类中显示的调用父类的构造函数.
          例子:
              function  parent ()
             {
                    this.first = parentFirst;
                    this.second = parentSecond; 
              }
              function child()
              {
                     this.inherrit = parent;
                     this.inherrit();
                     this.second = childSecond;
            }
              function parentFirst()
           {
                  alert(" parent First method call !");
            }
           function parentSecond()
            {
                  alert(" parent second method call !");
            }
            function childFirst()
            {
                  alert("child first method call !");
            }
            function childSecond()
            {
                  alert("child second method call !");
            }
            function  printClass()
            {
                  var newObj = new child();
                  newObj.first();
                  newObj.second();
            }
            printClass();
             发现最后打印出来结果是 parent first method call !   child second method    call !
          我们可以看到,first 和second 方法最先在parent类中定义,在child类中 second方法又被重载了.child类的构造函数的前2行的作用就是做了一个简单的原始继承操作.
先把parent的原型赋给child的inherrit方法,执行完parent的构造函数后parent的属性就全在child的属性列表里了.因为child中是用this来调用parent的构造函数的,javascript解释器会把parent中的this,child中的this 理解成一个作用域下的this,所以就产生了继承效果.
  2.   继承的第二种方式:  prototype方式.
        把父类对象赋给 子类的prototype属性.
        把我们的子类改一下:
        function child()
        {
                     this.second = childSecond;
         }
         加入   child.prototype = new parent;这一行语句,执行,发现和第一种方式得到同样的结果.
        用prototype 方式继承比调用构造函数方式更灵活.用prototype方式可以实现动态继承,比如你用prototype方式给父类动态增加一个属性或者方法,那么子类自动就会获得这个属性或者方法.  
           在javascript中你可以随意的给对象增加属性或者方法,但是当你给一个实例化的对象增加属性的时候,这个增加的属性只属于这个实例,例如:
   var newClass = new subClass();
  newClass.addprop = "新增属性";
如果想为该类的所有实例都增加一个属性或者方法,要用prototype,  例子
   var newClass = new child();
  child.prototype.addprop = "新增属性";
  这样newClass里就会有addprop这个属性了.
这也是我们给javascript内部对象增加属性或者方法的方式,比如 String.prototype.toString={return "aaa";},不过javascript的内部对象的prototype属性都是只读的,所以只能增加内部对象的属性,不能修改.
      突然感觉倒 prototype,用处原来如此之多,上边写的不过是其中一小步分啊.

posted on 2006-08-10 00:04 穷鬼 阅读(168) 评论(0)  编辑  收藏 所属分类: AJAX学习

只有注册用户登录后才能发表评论。


网站导航: