0

I have created an object literal in javascript using var keyword and assigned undefined properties and also methods. In the window.onload i first assigned values to properties then run methods, but in the run time they're still undefined.

window.onload = () => {
    obj.prop = ["a", "b"];
    obj.run();
};

var obj = {
    prop: undefined,
    run: () => {
        console.log(this.prop);
        for (let val of this.prop) {
            console.log(val);
        }
    },

};

The expected output should be :

"

["a","b"]

"a" 

"b"

"

but it shows the following :


undefined

TypeError : this.prop is not iterable at Object.run(?,the real object name is bloom but it errors "at Object.run") at window.onload

MaartenDev
  • 4,068
  • 5
  • 16
  • 28

1 Answers1

1

Because of usage of the arrow function the "this" points to Window. You can't use that in an arrow function like you do.

Try to write your run function with the function keyword.

Example with function binding:

 window.onload = () => {
        obj.prop = ["a", "b"];
        obj.run();
    };

    var obj = {
        prop: undefined,
        run(){
            console.log(this)
            console.log(this.prop);
            for (let val of this.prop) {
                console.log(val);
            }
        },
    };
MaartenDev
  • 4,068
  • 5
  • 16
  • 28
Karlan
  • 337
  • 1
  • 2
  • 10