Search code examples
javascriptjqueryprototype

jquery create prototype from object


I would like to cheat a little bit when creating prototypes

for example

var person = {
   name: 'John',
   age: 110,
   gender: 'm',
   ...
};

var employee = new Person(person);

function Person(args) {
   $.each(args, function(key, value) {
      this[key] = value; // Cannot create property 'key' on number
   });
}

console.log(employee.age);

In PHP this can be done like

function __construct() {
    $args = func_get_arg(0);            
    foreach ($args as $key => $value) {
        $this->$key = $value;
    }
    return $this;
}

Solution

  • The problem on your jQuery code is that 'this' is actually in the jquery each scope, so to actually prototype your new instance you need to do this:

    function Person(args) {
        var _this = this;
       $.each(args, function(key, value) {
          _this[key] = value;
       });
    }
    

    You can also achieve this without using jQuery:

     function Person(args) {
        for(var key in args){
            this[key] = args[key];
         }
     }