0
function DoSomething()
{
     var scope = this;
}

Consider the following methods of invoking it: Option 1:

var self= this;
$someElement.change(self.DoSomething);

Option 2:

var self= this;
$someElement.change(function(){self.DoSomething();});

Why is it that the when the change event is triggered, the first line of code results in scope being the element that triggered the event, but the second results in a scope that is the same as self but the second?

Since I don't understand the concept at hand here, it has been difficult for me to Google the correct search term.

k29
  • 641
  • 6
  • 26
  • Related: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – Jamiec Oct 09 '15 at 11:21
  • Because a function can be called with _.call_ and _.apply_, where the first argument represent the context ( _this_ ); therefore _this_ is contextual. – Ioan Oct 09 '15 at 11:21
  • Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – rafaelcastrocouto Oct 09 '15 at 11:29

1 Answers1

0

jQuery calls the given function within a context of original element.

Option 1:

You have passed self.DoSomething as a function.
jQuery will call self.DoSomething within a context of $someElement:

The following code is executed:

var self = this;
self.DoSomething.call($someElement);

function DoSomething()
{
    // this = $someElement
    var scope = this;
}

within DoSomething this is equal to callee - $someElement.

Option 2:

You have passed anonymous function as a function.
jQuery will call anonymous function within a context of $someElement:

var self = this; 
function() {
    self.DoSomething();
}.call($someElement);

function() {
    // this = $someElement, as well
    self.DoSomething(); // LOOK! You call self's method. Not within any context
}

function DoSomething()
{
    // default function call, default this is presented
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101