When executing the following code I get this error:
Uncaught TypeError: Cannot read property 'theTests' of undefined
$(document).ready(function() {
var Example = {};
Example = {
settings: {
theTests: $('.test'),
firstTest: Example.settings.theTests[0]
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
But if I do it this way:
$(document).ready(function() {
var Example = {};
Example = {
settings: {
theTests: $('.test'),
firstTest: $('.test')[0]
},
test: function() {
var theTests = $('.test'),
firstTest = theTests[0]
}
}
Example.test();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
Defining it inside the settings, or in the function, both of them work this way.
So my question is:
Why when defining the firstTest
property based on the theTests
property inside the settings
doesn't work?
Edit:
Like suggested by duplicate I checked this question but I'm not looking for a way to do it. I'm trying to understand why it doesn't work.