接下来,我们介绍如何实现封装
其实,在前面的教程里面我们已经说明了如何将私有的方法封装做类的内部,放置继承类对其的改变。在定义的类内,通过 var来定义的变量和函数,将视为私有函数,子类即不能继承,也不能访问。
比如下面的代码,var部分是不可以被外部及子类访问的。但是可以通过类内的公开方法访问私有变量和方法。比如getValue中,可以返回私有变量p的值。
示例的代码如下:
/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;
});
})();