0

I can't find a way to get this kind of thing working :

// I want to achieve managing the structure of the object here and only here
var objectAPropertiesList = ["aProp", "bProp", "cProp"];

// Object with constructor
function ObjectA(properties) {
    objectAPropertiesList.forEach(function (property) {
        this[property] = properties[property];
    });
}
// instantiation
myObjectA = new ObjectA({"aProp": 1, "bProp": 2, "cProp": 3});

// keeps giving me '{}' !
console.log(JSON.stringify(myObjectA));

Can someone explain how please ?

St3an
  • 726
  • 1
  • 6
  • 21
  • 1
    Use `for (const property of myObjectPropertiesList) {` and it'll work. – Bergi May 10 '17 at 08:52
  • thank you ! @hindMost : I thought `["blah blah", "anything', ...]` was the array notation whereas `{"propA":"valueA", "propB":"valueB", ...}` was the Object one ?... – St3an May 10 '17 at 08:55
  • 1
    @Bergi I don't see the relation between my post anf the one you indicated as being a duplicate... – St3an May 10 '17 at 09:38
  • It tells you why the `this[property]` assignment inside the callback doesn't work – Bergi May 10 '17 at 16:47
  • 1
    ok I understand. `.forEach()` calls another function here, I didn't pay attention to it ! By the way, I [just see](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) that one can pass a *thisArg* as second argument to `.forEach`, which allows to use it too – St3an May 11 '17 at 10:04

0 Answers0