(example is from the book but I don't seem to get it)
function User (properties){
for( var i in properties){
(function(){
this["get"+i] = function () { return properties[i];};
this["set"+i] = function (valueOne) { properties[i] = valueOne; };
}) ();
}// END for
}// END User
var userOne = new User ({ name: "Billy", age: 35 });
userOne.getname();
When I run this, User does not have getname
method. How can I make the privileged method works?
This is because you used an immediately invoked function
Remove it and it will still not work, but your methods will be there. To get it fully working you should preserve
i
The latter issue is not as interesting (though related to) the first one.
Javascript has only what is known as "function scope" meaning that the only thing that limits function scope is...well...a function. Therefore, a common pattern is to use IIFEs like this inside of for loops or in many places where you don't want variables to leak.
However, the
this
parameter in javascript is weird. Understand the following and it will save you a ton of hassle:this
in javascript is no different from any other parameter.Let me explain.
There are four ways to invoke a function in javascript.
If you were always to use the
.call
form all ambiguity would be gone and you can see thatthis
is exactly like every other parameter. However that's extra syntax and people prefer using the simpler form which means you have to consider the rules for what is "this".Therefore what you are doing in your example is placing getters and setters on the global
window
object.I'm going to make a statement here that your book probably doesn't agree with but that I've picked up from years of learning, working with, and teaching javascript:
Don't use the
new
andthis
keywords.These two keywords introduce a ton of concepts into JS that are confusing and really - unless you're making something very performance sensitive (you're not, I know you think you are, but you're not) - not necessary. Instead create new objects simply like this:
if you absolutely must have getters and setters this will do it:
Although I'll go even further to state that getters and setters are not terribly useful in js, and when you DO use them it is standard to follow a pattern similar to what knockout does.