关键字: js 封装 继承

封装主要用意在于将实现细节隐藏,提供给客户端的只是定义良好的接口,在js中的封装同其它语言中的封装并无差异,最为简单的封装就是通过function 函数初始化类。
例如定义:
function Shape(){
         this.init = function(param1,param2){
             this.param1 = param1;
             this.param2 = param2;
            }
        }
js中函数本身就是类,我们可以通过Shape函数的prototype属性为该类添加方法,如下所示
  Shape.prototype = {
               method1:function(){alert(this.param1)},
               method2:function(){alert(this.param2)}
 }
 下面创建一个Shape实例对象
     var shape = new Shape();
     shape.init('method1','method2');
     shape.method1();
     shape.method2();
   在js中并无继承机制,但可以通过将prototype中保存的变量逐一复制也可实现类似java语言中的继承,如下所示:
Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};
function Square(){
       /*code here */
}
 Square.prototype = Object.extend(new Shape(),{method3:function(){alert('square')}});
 下面创建Square实例,进行测试:
var square = new Square();
square.init('square method1','square method2');
     square.method1();
     square.method2();
      square.method3();

完整代码如下:

Js代码 js 类的封装和继承(2)
  1. <script>   
  2. function Shape(){   
  3.          this.init = function(param1,param2){   
  4.                               this.param1=param1;   
  5.                               this.param2=param2;   
  6.                       }   
  7. }   
  8.   Shape.prototype={   
  9.      method1:function(){alert(this.param1)},   
  10.      method2:function(){alert(this.param2)}   
  11.  }   
  12.     var shape = new Shape();   
  13.      shape.init('method1','method2');   
  14.      shape.method1();   
  15.      shape.method2();   
  16.   
  17.     Object.extend = function(destination, source) {   
  18.         for (var property in source)   
  19.             destination[property] = source[property];   
  20.         return destination;   
  21.     };   
  22.     function Square(){   
  23.        /*code here */  
  24.     }   
  25.     Square.prototype = Object.extend(new Shape(),{method3:function(){alert('square')}});   
  26.   
  27.     var square = new Square();   
  28.     square.init('square method1','square method2');   
  29.      square.method1();   
  30.      square.method2();   
  31.       square.method3();   
  32. </script>  

相关文章:

  • 2021-06-26
  • 2022-02-18
  • 2021-08-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
  • 2022-12-23
  • 2021-07-20
  • 2021-06-28
  • 2022-01-19
相关资源
相似解决方案