2007/10/25

javascript java style package and constructor demo

javascript java style package and constructor demo

//------------------------------------
// declaration
/** create package pkg. keep the exits package */
var pkg = (pkg) ? pkg : {};
/** create class Test */
pkg.Test = (pkg.Test) ? lgr.warn("pkg.Test already exists, ignore.") : function (str) {
/** private member */
var _str;
/** property get */
this.getStr = function () {
// not need "this." for the private variable
return _str;
}
/** property set */
this.setStr = function (str) {
// not need "this." for the private variable
_str = str;
// smalltalk style return this
return this;
}
}

//------------------------------------
// test pobject, load the package before execute
var test = new pkg.Test ("init test");
test.setStr("modified");
// another object
var test2 = new pkg.Test ("init test2");
test2.setStr("modified2");

// inspect second object, should display "test2"
alert("test2 is" + test2.getStr());
// inspect first object, should display "test"
alert("test is" + test.getStr());
// try to inspect private variable, should display "undefined"
alert("try to access private member _str from outside. result is" + test._str);

No comments: