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...
2 Answers 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...
2 Comments
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 thereYou 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...
thisnever refers to your function; it refers to the newly-created object. You can useObject.assign()to copy the parameter object properties into the new object. However you can also use afor ... inloop, which will not affect the value ofthis.