0

In the process of learning object literals and was experimenting with the following code. I'm trying to get the values of inputs based on the css class (.one,.two). I have created the two 'variables',oneInput and twoInput to get the elements that match each class. Then I've assigned the two variables to the array, which I'm planning to access within getInputValues function but the array is returning undefiend. I did read a few threads about object literals and the use of 'this' but not sure how to overcome this situation.

However, if I create another function inside the object and return the same array it works but I'd like to know if I can achieve the same with this current implementation.

var myObj = {
  oneInput: $('.one'),
  twoInput: $('.two'),
  arr: [this.oneInput, this.twoInput],

  getInputValues: function() {
    console.log(this.arr);
  },

  eventBind: function() {
    this.oneInput.on('blur', this.getInputValues.bind(this));
  }
}

myObj.eventBind();
.one,
.two {
  display: block;
  margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="one" />
<input type="text" class="one" />
<input type="text" class="one" />
<input type="text" class="one" />

<hr />

<input type="text" class="two" />
<input type="text" class="two" />
<input type="text" class="two" />
<input type="text" class="two" />

Any help, adivce is massively appreciated.

Jayonline
  • 143
  • 11
  • 1
    This article explains the issue and the approach to use very well: https://clubmate.fi/self-referencing-object-literal-in-javascript/ – Rory McCrossan Jan 30 '20 at 16:17
  • 1
    *"but I'd like to know if I can achieve the same with this current implementation."* No. the object doesn't exist at the moment the arrays is created. `this` doesn't refer to the object. – Felix Kling Jan 30 '20 at 16:17
  • 'this' inside the function is not the same 'this' inside the object. – Nawed Khan Jan 30 '20 at 16:18
  • `No. the object doesn't exist at the moment the arrays is created` Sorry, Felix, I didn't quite understand that. :( – Jayonline Jan 30 '20 at 16:23
  • Great article Rory! Many thanks for sharing... – Jayonline Jan 30 '20 at 16:27
  • 1
    When you do `{foo: [bar()]}` this is the order of operations: Call function `bar()`, remember the return value. Create the array and set the first element to be the remembered value. Create the object and set the array as the value of the `foo` property. In short: array elements > array (property values) > object. At the moment the array elements are evaluated the object doesn't exist yet and therefore none of the elements can refer to a property of the object. It works if you put the array inside a function because the function is called some time *after* the object was created. – Felix Kling Jan 30 '20 at 16:43
  • Many thanks for the explanation, Felix - much appreciated! – Jayonline Jan 30 '20 at 16:56

0 Answers0