0

I have the below code, and have been trying and been reading and yet cant figure out how to loop over the params array/object, and set the key value pairs on to 'this' so I can access them as per the last line in my below code.

I believe it is because of the scope, that 'this' doesnt refer to my function anymore when it is in the for loop, but how can I get the scope in there? I found that you can add it as a secondary parameter to a foreach loop, but I can not get a foreach loop working over an associate array.....

I would like to be able to access any value in the array passed to the function batman, later on, in the way my example shows to print out lname.

function batman(id,params){
  this.id=id;
  for(.....params.....){
    // this.key=val;
  }
  
}


x=new batman("my_id",{fname:"jason",lname:"bourne"});
console.log("id: "+x.id); // works fine
console.log("fname: "+x.fname); // would like to get this to work...

1
  • this never refers to your function; it refers to the newly-created object. You can use Object.assign() to copy the parameter object properties into the new object. However you can also use a for ... in loop, which will not affect the value of this. Commented Nov 6, 2018 at 15:07

2 Answers 2

2

Do you mean like this? It seems like your issue is in parsing the key/value pairs in the params object. Run the snippet to see it work...

function batman(id,params){
  this.id=id;
  for(var key in params){
    this[key]=params[key];
  }
}


x=new batman("my_id",{fname:"jason",lname:"bourne"});
console.log("id: "+x.id); // works fine
console.log("fname: "+x.fname); // hey look! this works fine now...

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

2 Comments

ah! i used this.key and not this[key] . Much appreciated!
To add to the answer: key in the loop is a string. So you need to wrap the key in square bracket to assign it. What you are doing is assigning value to x.key. so if you console.log(x.key) you'll see the value of the last loop there
1

You can use a forEach on the keys of params in order to set the properties of this.

I've updated batman to Batman, for the sake of sticking to convention.

function Batman(id,params){
  this.id=id;
  Object.keys(params).forEach(key => this[key] = params[key])
}


x=new Batman("my_id",{fname:"jason",lname:"bourne"});
console.log("id: "+x.id); // works fine
console.log("fname: "+x.fname); // would like to get this to work...

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.