1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Javascript: What causes {this} to happen?

Discussion in 'Programming' started by mumfry, Sep 12, 2015.

  1. #1
    Hello
    Am going to get straight to it.
    My question is about the "this" keyword and a particular situation i came across that i find very confusing.

    Some code for explanation.
    Eaxmple #1
    var Example = function(){
     this.something = 5; 
     this.firstFunction = function(){
            this.nextFunction;
           // console.log(this) in here equals to this object;
       };
      this.nextFunction = function(){
          // but console.log(this) in here equals to the window object even though it was called from the function above (this.firstFunction);
         this.something = 8 ;//so this won't work, says that this.something is undefined
    };
    };
    
    $("body").on("click", ".startbutton", function(){
         var _example = new Example();
               _example.firstFunction();
    });
    Code (JavaScript):
    So whats happening here is that when user clicks, a new instance of the Example class is created
    and begins with the firstFunction(), found inside the class. Then this is what i dont quite get, when i call the nextFunction() from inside of the firstFunction(). The "this" keyword inside of nextFunction() no longer represents the object it's in but instead represents the window object instead.

    I can get it to work only if I do this
    Eaxmple #2
    var Example = function(){
     this.something = 5; 
     this.firstFunction = function(){
            detourFunction();
       };
      this.nextFunction = function(){
          // now console.log(this) in here equals to this object;
         this.something = 8 ;//and this value can now be changed
    };
    };
    var _example;
    
    function detourFunction(){
      _example.nextFunction();
    }
    
    $("body").on("click", ".startbutton", function(){
          _example = new Example();
               _example.firstFunction();
    });
    Code (JavaScript):
    But would like to know, why in the first example does the "this" keyword change from representing the current object
    to the window object even though it was called from inside of the current object.

    Hopefully someone gets this(haha) cause i don't fully get it. The "this" keyword can be very tricky but i know there are many competent programmers here at Digitalpoint who can help me understand this a little better.

    Any insights on this would be greatly appreciated.

    Thanks
     
    mumfry, Sep 12, 2015 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #2
    "this" is a pain in the ass once events are involved. The moment you register it as an event handler, "this" refers in most browsers to the EVENT and not the method being called. The method is basically "downgraded" to function status with any associations to the parent object being broken.

    Which is an insanely massive truckload of idiotic BS that makes objects WAY less useful than they could be -- but did we mention we're talking about JavaScript which much like every other C dialect with objects basically has objects shoe-horned into them any-old-way. (Sorry, Object Pascal / Modula / SmallTalk guy talking)

    No matter how you 'break' the scope to try and recover "this" into something meaningful? It's not going to work. That's why using object methods as event handlers are universally a disaster. The BEST you can usually hope for is to attach a copy of your object to the element on which the event fires, so you can do:

    var target = e.target || e.srcElement;

    To get hold of the tag that fired the event, so you can access the object via that.

    Of course, you've got jQuery-tardery in there dicking with it who knows how -- so it's likely even more broken than you are thinking.

    Bottom line, "this" is ***ed up the MOMENT you have an event handler installed, even in objects you create and handle in that handler. :( It's just one of those things that makes you want to punch the people who created JavaScript in the face as there's no rhyme nor reason to when it will or will not break.
     
    deathshadow, Sep 12, 2015 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Oh, actually, the jQueryTard BS is breaking your scope. This should work:

    var Example = function(){
    	this.something = 5;
    	this.firstFunction = function(){
    		detourFunction();
    	};
    	this.nextFunction = function(){
    		// now console.log(this) in here equals to this object;
    		this.something = 8 ;//and this value can now be changed
    	};
    };
    
    function detourFunction(){
    	Example.nextFunction();
    }
    
    function handleExample() {
    	Example.firstFunction();
    }
    
    $("body").on("click", ".startbutton", handleExample);
    Code (markup):
    But don't quote me on that. Again, SHOULD. Across different browser engines? Yeah, good luck with that.
     
    Last edited: Sep 12, 2015
    deathshadow, Sep 12, 2015 IP
  4. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #4
    I wish JQuery would be BANNED. I detest pages that load 384K of code just to do what can be done in a few BYTES. And it is especially frustrating if one is still using dial-up for whatever reason.

    Too many crappy programmers out there that THINK they are saving time and effort using such a clusterf*** of code like JQuery when in fact if they would learn JS things would code and flow much better.
     
    mmerlinn, Sep 12, 2015 IP
    deathshadow likes this.