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 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:
ReplyDeletemyObj.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.
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.
ReplyDeleteI'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
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
ReplyDeletethis 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.
ReplyDeleteGenerally, 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:
http://stackoverflow.com/a/3320706/87170
http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
http://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/this_Operator
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.
myObj.src.A[0] would be correct in this context because this references its immediate parent.
ReplyDelete