This is probably pretty easy, yet I am confused, so maybe I might still learn something more today. I am trying to do the following:
var myObj = {};
myObj.src = {}
myObj.src.A = ['1.png','2.png','3.png'];
myObj.A = new Image();
myObj.A.src = this.src.A[0];
This will result in an Uncaught TypeError: Cannot read property 'A' of undefined error.
When I use myObj.src.A[0] instead of this it is working fine.
What would be the correct way to use this in this context?
The
thiskeyword is always different depending on the scope involved. In the code snippet you’ve posted above, assuming that you’re just putting this in the document somewhere in the head,thisrefers to the page itself. So, it’s fairly obvious at that point thatthis.src.Awill be undefined. If you were to apply an event to it with a delegate such as:The
thiskeyword receives a new scope belonging to the owner of the delegate (in this case myObj).thisis very easy to track so long as your clearly define your scopes and your scope boundaries.