Hene
Hene

Reputation: 159

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;
}

Upvotes: 0

Views: 89

Answers (3)

Aboca
Aboca

Reputation: 575

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];
     }
 }

Upvotes: 2

alexP
alexP

Reputation: 3765

Use bind for getting the right scope

function Person(args) {
   $.each(args, function(key, value) {
      this[key] = value; 
   }.bind(this)); //Use bind for getting the right scope
}

Upvotes: 1

Amit Wagner
Amit Wagner

Reputation: 3264

the problem is "this" refers to the each function and not the actual Person you can change it to arrow function an it will work

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

var employee = new Person(person);

function Person(args) {
   $.each(args, (key, value) => { //changed to arrow function to keep this in the same scope
      this[key] = value; // Cannot create property 'key' on number
   });
}

console.log(employee.age);

Upvotes: 3

Related Questions