1

I am initialising an object properties with dynamic keys and values from within my object's prototype. So I do this:

var base_proto = {
            init_props : function (props){

                $.each(props, function(key, value) {
                    this[key] = value;      
                });
            }
        }

This does not work and just return an Object with no properties.

But when I try this.notDynamicName = notDynamicContent; in init_props it worked.

So basically, the dynamic assignment of keys and value is the problem.

So how can I deal with that?

Your responses would be greatly appreciated.

iamjc015
  • 2,127
  • 6
  • 25
  • 61

1 Answers1

4

The issue is that you have a function, which creates a new scope. So the this, is not the this you expect.

You can do this:

var base_proto = {
        init_props : function (props){
            var _this = this;
            $.each(props, function(key, value) {
                _this[key] = value;      
            });
        }
    }

Or even better:

var base_proto = {
        init_props : function (props){

            for(var k in props)
                this[k] = props[k];      
            });
        }
    }
Niels
  • 48,601
  • 4
  • 62
  • 81
  • it worked but not with this[key] = value. I have to assign this into a variable _this like what you've said in your second answer. Amazing Aloha! – iamjc015 Jun 07 '15 at 13:59