-2

What's the difference in writing the empty arrays inside the method,

var example = {
    calcMethod: function() {
        this.array1 = [];
        this.array2 = [];
    }
};

instead of writing them as object parameters?

var example = {
    array1 : [],
    array2 : []
};

to eventually fill them with data.

  • 1
    None of this is valid Javascript. – Sani Huttunen Oct 26 '18 at 17:18
  • 2
    Your question is really about the use of the `this` keyword. See [this](https://stackoverflow.com/questions/41496958/this-does-not-work-properly-in-another-event-im-clueless-as-to-why/41496969#41496969). But your specific syntax `let = object` is invalid. It should be something like `let o = {...}` – Scott Marcus Oct 26 '18 at 17:19

1 Answers1

2

Despite the illegal javascript syntax I'll answer your question.

The difference is that calcMethod must be called before array1 and array2 are defined in the first snippet. Otherwise they'll be undefined:

let object1 = {

calcMethod: function() {
        this.array1 = [1];
        this.array2 = [2];
    }
}

let object2 = {
    array1: [3],
    array2: [4]
}


console.log(object1.array1);  // undefined
console.log(object1.array2);  // undefined

object1.calcMethod();

console.log(object1.array1);  // [1]
console.log(object1.array2);  // [2]

console.log(object2.array1);  // [3]
console.log(object2.array2);  // [4]
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79