Auto setter/getter currying
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 last-used 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.
var that = this;
for ( var i in properties ) {(function(){
// Create a new getter for the property
var currentProperty = i; // Error correction.
that[ "get" + i ] = function() {
return properties[currentProperty]; // Error correction: can't use "i" here.
};
// Create a new setter for the property
that[ "set" + i ] = function(val) {
properties[currentProperty] = val; // Error correction: can't use "i" here.
};
})(); }
}
// Create a new user object instance and pass in an object of
// properties to seed it with
function doAction() {
var user = new User({
name: "Bob",
age: 44,
team: "Wests Tigers"
});
// Just note that the name property does not exist, as it's private
// within the properties object
// the newly generated functions
console.log(user.getname());
console.log(user.getage());
...