0

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;
}
2
  • So what is the problem here. What do you expect us to do? What kind of solution that you are expecting? Commented Aug 24, 2018 at 11:39
  • 1
    Well assigning this[key] = value is not working. I would like to create a Person out of object instead of creating something like this: var employee = new Person(person.name, person.age, person.gender, ...); and function Person(name, age, gender, ...) this.name = name etc. Commented Aug 24, 2018 at 11:43

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Might add that the difference between this and the OP's PHP version is that the PHP version uses a loop instead of a callback function (so no scoping issue).
Awesome! Thank you.
Note that arrow functions might cause compatibility issues: caniuse.com/#feat=arrow-functions
Or just use bind(this) $.each(args, function(key, value) { this[key] = value; }.bind(this));
2

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

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.