Reputation: 11822
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?
Upvotes: -1
Views: 607
Reputation: 3642
this
in JavaScript depends heavily on the context in which a function is called. If your code is (as it looks to be above) just hanging out in a script tag in the page, then this
is going to be the "global" context -- which in the browser is the window
object.
Generally, this
refers to the object/scope a function belongs to, but there's a number of special (and useful) cases that happen because functions are first class values that can be assigned to different objects and invoked in various contexts.
Some lengthy elaboration others have written might be helpful:
It can seem a little tricky at the start, particularly if you're used to languages in which this
is always one thing, but after you learn a few rules it becomes fairly straightforward and actually very useful.
Upvotes: 1
Reputation: 37543
The this
keyword 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, this
refers to the page itself. So, it's fairly obvious at that point that this.src.A
will be undefined. If you were to apply an event to it with a delegate such as:
myObj.click = function() {
alert(this.src.A[0]);
}
The this
keyword receives a new scope belonging to the owner of the delegate (in this case myObj). this
is very easy to track so long as your clearly define your scopes and your scope boundaries.
Upvotes: 1
Reputation: 13476
this
does not refer to var myObj
in the case of your code. It is likely that if you are not inside the scope of a function or an objects method then this
is referring to the DOM window which has no attribute src.A
Upvotes: 1
Reputation: 6351
myObj.src.A[0]
would be correct in this context because this
references its immediate parent.
Upvotes: -1
Reputation: 14834
this
refers to the object context in which the code is executing. So if an object has a method aMethod
, then inside aMethod
this
references the object that owns it.
I'm assuming your code there is running in the global namespace, so this
is undefined. Really you just want myObj.A.src = myObj.src.a[0];
.
http://www.quirksmode.org/js/this.html
Upvotes: 3