js 类的封装和继承(2)
封装主要用意在于将实现细节隐藏,提供给客户端的只是定义良好的接口,在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();
完整代码如下:
- <script>
- function Shape(){
- this.init = function(param1,param2){
- this.param1=param1;
- this.param2=param2;
- }
- }
- Shape.prototype={
- method1:function(){alert(this.param1)},
- method2:function(){alert(this.param2)}
- }
- var shape = new Shape();
- shape.init('method1','method2');
- shape.method1();
- shape.method2();
- 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')}});
- var square = new Square();
- square.init('square method1','square method2');
- square.method1();
- square.method2();
- square.method3();
- </script>