...

View Full Version : a javascript defineSetter implement



never-online
05-03-2007, 05:04 PM
look the codes as following or click a demo URL::)
demo:http://www.never-online.net/code/js/defineSetter/defineSetter.html


function jsClass() {};
jsClass.prototype = {
value: 'never-online',
URL: 'http://',
blog: 'blog',
name: "jsclass",
println: function () {
alert(this.value);
alert(this.blog);
alert(this.name);
alert(this.URL);
},
write: function (value) {
document.writeln(value);
}
};
jsClass.defineAllSetter();
jsClass.defineSetter('value',
function (arg) {
if ("a"===arg) return "Absolute a";
return "not a";
}
)
var o = new jsClass();
o.setValue('a');
o.setURL("<a href='http://www.never-online.net/blog'>http://www.never-online.net</a>");
o.setName("never-online");
o.setBlog("never-online's blog");
o.println();


as you see, the jsClass do not has the setValue, setURL setName and etc. method to set the jsClass property, and i add a method to jsClass, make the class has set method with all property, that is defineAllSetter()

how to implement defineAllSetter method?

we know the js has feature which is dynamic to add method
the principle code like this:



var o = { property:'i am a property' }
o['printProperty']=function () {
alert(o.property);
}


and the all code with defineSetter as following:


var _defineSetter = function (self, p, hdle) {
if (!p || !self || "function"!=typeof self)
return null; p = String(p); self = self.prototype;
if (p && "function"!=typeof self[p]) {
var n = (function _n (n) {
n = String(n); for (var i=0; i<n.length; i++) {
var letter = n.substring(0,1).toUpperCase();
n = n.substr(1);
if (/[a-z]/i.test(letter))
return 'set'+letter+n;
}; return null;
}) (p);
if (n && hdle && "function"==typeof hdle)
self[n] = new Function("v", "this." +p+ "=" +hdle+ ".apply(this,[v]);");
else
self[n] = new Function("v", "this." +p+ "=v;");
return self[n];
}; return self;
};

Function.prototype.defineAllSetter = function (hdle) {
for (var i in this.prototype)
_defineSetter.apply(this, [this,i,hdle]);
return this;

};

Function.prototype.defineSetter = function (p, hdle) {
return _defineSetter.apply(this,
[this].concat(Array.prototype.slice.call(arguments,0)));
};


the finished demo URL is
http://www.never-online.net/code/js/defineSetter/

david_kw
05-03-2007, 05:40 PM
how to implement defineAllSetter method?


Are you asking a rhetorical question? Or does something not work?

Maybe you meant to post it here?

http://www.codingforums.com/forumdisplay.php?f=19

david_kw



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum