Skip to main content

JavaScript "this" confusion



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?


Comments

  1. 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.

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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:


    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.

    ReplyDelete
  5. myObj.src.A[0] would be correct in this context because this references its immediate parent.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.