Auto setter/getter currying, Mike experiments!
Resig Pro-JavaScript techniques, p37
HTML
<input type="button" onclick="doAction();" value="doAction()"><br>
<br>
<br>
<input name="TestField" value="" id="TestField"></form>
JavaScript
function User( properties ) {
// From Pro JavaScript Techniques, John Resig, p.37
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
// Erratta in Resig's book: he uses "this" within the for/loop
// function that creates the setters/getters, thinking that it
// refers to User function, but it doesn't. Due to function scope
// it gets reset to the global, i.e. the DOM window. You need to
// use the "var that = this;" trick and then refer to
// "that" instead.
// The second error is his use of the "i" variable in the return
// of the setter/getter functions created. "i" is of a higher scope
// and so is not the correct property when the getter/setter is called.
// It only works in John's example call because getage is the last function
// he defines, and so "i" is still at its highest value. A getname() call after
// setage() call will actually return the age too. We can get around that by
// capturing "i" at the correct value by using the "currentProperty" variable
// as I have done below.
// I've modified the function so that the properties are private (otherwise, why
// require setters/getters in the first place). Also, the function checks to see
// that the current property isn't a function itself before creating the setter/getter
// for it. If that property *is* a function, then it's assigned to User function
// as an ordinary, public method by assigning it to "that" (the User function's "this")
// although I'm not sure what the point of doing this might be.
var that = this;
var privateProperties = [];
this.getage = function () {
return "the age = " + privateProperties["age"];
}
this.setteam = function () {
console.log('Sorry, you cannot set the team property');
};
for ( var i in properties ) {
if(typeof properties[i] === "function") {
that[i] = properties[i];
}
else {
...