EasyJS 教程四 - 实现继承及重载

来源:互联网 发布:伊的家网络销售犯法吗 编辑:程序博客网 时间:2024/06/05 04:16

继承和重载机制是面向对象编程的重要概念,有了继承和重载,在程序设计中,我们将很容易实现开闭原则,OK,我们来复习一下开闭原则,所谓开闭原则,就是对扩展开放,对修改封闭。我本人做一家美国公司从事编程工作,我们的客户包括数百家美国的银行和信用卡财务公司,再手机开发中,在产品组中,我们开发一套标准化的程序,供项目组使用,项目组根据客户的需求来定制产品。这个思路确实很好,可以有效的利用资源,降低企业的成本。但是,在实际执行中,因为架构的设计及开发工具的限制,成为一个反开闭原则的案例。无法通过扩展来实现业务需求的更改,而是通过修改来完成。于是公司有了N个版本的互不兼容的程序,当产品组更改一些bug的时候,所有的项目组不得不通过合并代码来维护产品,每次合并后,必须经过大量的测试,浪费大量的人力物力和财力。


现在,我们完全可以实现JS的继承,重载,还是用上面的代码来说明:

/app/com/fern/base_foo.js

(function() {  var baseFoo = function() {  var self = arguments[0] || this;  var _super = ExtendClass(this, JOObject, self);  var p = 10; //This is a private variable  var showBaseValue = function() {    console.log("the BaseFoo private p = " + p);  };  this.getValue = function() {    return p;  };    this.sayHello = function() {    console.log("Hello from BaseFoo");  };  this.showValue = function() {    showBaseValue();    console.log("The value is: " + self.getValue());  }; };  JsLibrary.register("com.fern.BaseFoo", baseFoo);})();


/app/com/fern/foo.js

(function() {  var foo = function() {    var self = arguments[0] || this;    var _super = ExtendClass(this, JsLibrary.classForName("com.fern.BaseFoo"), self);    var p = 20; //This is a private variable    var showBaseValue = function() {      console.log("the foo private p = " + p);     };    this.getValue = function() {      return p;    };    this.sayHello = function() {     _super.sayHello();     console.log("Hello from Foo");    };   this.showValue = function() {     showBaseValue();     _super.showValue();    };   };  JsLibrary.import("com.fern.BaseFoo", function() {    JsLibrary.register("com.fern.Foo", foo);    }, function(err) {       throw err;    });})();



演示的代码在github中有,把WebContent导出,然后放置到你的web服务器上,访问该目录,用firefox或者chrome,进入到开发工具窗口中,可以用这样的方法调用。下面的贴图可以看到子类可以覆盖父类的方法,也可以通过_super来调用父类的方法。