views:

307

answers:

2

It would be exceedingly handy if I could do this:

var MyObject = function(param1, param2, ... paramN)
{
    this.var1 = stuff;
    this.var2 = moreStuff;
    .
    .
    .
    this.varN = nStuff;

    this.validate = function()
    {
        for(var current in this)
        {
            alert(current);
            //validate all member variables (even this function I suppose)
        }
    };
};

This however does not seem to do what I would want. I realize that the loop would eventually have to loop over it's parent function (which also, not surprisingly, does not happen).

Is this impossible because the 'this' in the second function refers to the second function and not the first? Or is the keyword 'this' only a declaration operator for a public member and not a reference to the outer object ?

I figure getting what I want this way is not possible but is there another way I can go about achieving this behaviour ?

A: 

How are you calling validate?

The following code works fine for me:

var MyObject = function(){
    this.var1 = 'stuff';
    this.var2 = 'moreStuff';
    this.varN = 'Stuff';

    this.validate = function()
    {
        for(var current in this)
        {
            alert(current);
        }
    };
};

var m = new MyObject();
m.validate();
Triptych
When I run this all the members are 'undefined'
+1  A: 

I think you're trying to get the value of the member and going about it the wrong way so try this:

   var MyObject = function() {
     this.var1 = 'var 1 value';
     this.var2 = 'var 2 value';
     this.varN = 'var n value';
     var self = this;

     this.validate = function() {
       for (var member in self) {
         if (!self.hasOwnProperty(member) || typeof(self[member]) === "function") continue;
         alert(self[member]);
       }
     };
   };

   var m = new MyObject();
   m.validate();

To explain: the loop check first if the property is a user defined property as opposed to being inherited from the Object object. It also checks that the member is not a function (like validate()) it then alerts the value of the member.

The hasownproperty check is recommended by Douglas Crockford (father of JS) as best practice when iterating over memebers.

Hope this helps,

Darko

EDIT: Forgot to mention self - i included this because its the standard way of making sure that your this is actually what you want it to be.

Darko Z
Looks good. Thanks for your help.
Kudos for adding function check. People always seem to forget that.
seth
Glad I could help. Seth, agreed!
Darko Z