Inside John Resig\'s book \"Pro Javascript techniques\" he describes a way of generating dynamic object methods with the below code:
// Create a new user obj
You can always force another this
for any function call, using the apply
method.
(function() {
// Create a new getter for the property
this["get" + i] = function() {
return properties[i];
};
// Create a new setter for the property
this["set" + i] = function(val) {
properties[i] = val;
};
}).apply(this);
Here is how to do it. You need to save the context into another variable. The other option is not to do this inner function that you are doing in the for loop.
// Create a new user object that accepts an object of properties
function User( properties ) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
var that = this;
for ( var i in properties ) { (function(){
// Create a new getter for the property
that[ "get" + i ] = function() {
return properties[i];
};
// Create a new setter for the property
that[ "set" + i ] = function(val) {
properties[i] = val;
};
})(); }
}
Option 2:
// Create a new user object that accepts an object of properties
function User( properties ) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
for ( var i in properties ) {
// Create a new getter for the property
this[ "get" + i ] = function() {
return properties[i];
};
// Create a new setter for the property
this[ "set" + i ] = function(val) {
properties[i] = val;
};
}
}
Is this code from the book? I have the book, but I haven't read through it.
It's an error in the book. Check the errata: http://www.apress.com/9781590597279
Inside the anonymous function, this
is the global window
.
You could make it work by adding .call(this, i)
after it.
function User(properties) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
for (var i in properties) {
(function(i) {
// Create a new getter for the property
this["get" + i] = function() {
return properties[i];
};
// Create a new setter for the property
this["set" + i] = function(val) {
properties[i] = val;
};
}).call(this, i);
}
}
The this
in the inner self-executing function is not the same as the this in the outer User
function. As you noticed, it refers to the global window
.
The problem is fixed if you slightly modify the code by adding a variable that refers to the outer this
.
function User(properties) {
var self = this;
for (var i in properties) {
(function() {
self["get" + i] = function() { /* ... */ };
self["set" + i] = function() { /* ... */ };
})();
}
}
That said, I'm not sure why the anonymous self-executing function is even needed here, so you have the simpler option of just leaving it out entirely, like this:
function User(properties) {
for (var i in properties) {
this["get" + i] = function() { /* ... */ };
this["set" + i] = function() { /* ... */ };
}
}