jim
jim

Reputation: 49

Javascript this and that with callbacks

When using var that = this for callbacks, why does the callback function have to be function() {that.myFn()} instead of that.myFn ?

For example:

var obj = {

  foo: function(fn) {
    console.log('--foo--', this);
    fn();
  },

  bar: function() {
    console.log('--bar--', this);
  },

  render: function() {
    var that = this;

    // this line works
    this.foo( function() {that.bar()} );

    // this line doesn't work
    this.foo(that.bar);
  }

}

obj.render()

Upvotes: 0

Views: 100

Answers (3)

slackOverflow
slackOverflow

Reputation: 177

when you invoke a function on a property like

myObject.myFunction();

it automatically binds the this value to that object, whereas simply getting a reference to that function object like so:

var x = myObject.myFunction;
x();

does not imply any "this". The first statement simply sets x to the same function as is referenced by that property of myObject.

wrapping it in a function like so:

var x = function(){ myObject.myFunction()};
x();

does invoke myFunction with myObject as bound to "this".

You can also use the javascript Function.prototype functions "call", "apply", and "bind", instead, like so:

var x = myObject.myFunction.bind(myObject, parameterOneIfAny);
x();

which returns a function with an explicitly bound "this" value of "myObject". Its just a part of the javascript function system that function objects don't save a "this" context (or rather default this to the environment "global" object in cases where you don't set this) unless invoked with property syntax object.function() or explicitly bound with object.function.bind(object)

finally, if you call any function reference with new as in

var x = myObject.myFunction.bind(myObject, parameterOneIfAny);
var y = new x();

this is instantiated as a fresh object, and passed as the return value, which is the basis for javascript's fake "class" syntax. So in this case, x is invoked as a constructor, and its this value is returned, making y a 'new' x.

Finally, javascript strict mode will call you out if you try to use this in a function that has not been invoked with a this context, rather than the non-strict behavior of defaulting this to the window object.

Upvotes: 2

Planetary Dev
Planetary Dev

Reputation: 51

As @slackOverflow says. Here a link that will help to understand https://developer.mozilla.org/de/docs/Web/JavaScript/Referen‌ce/Operators/this

or try this. It's a nice post that may help too. http://ryanmorr.com/understanding-scope-and-context-in-javas‌​cript

Upvotes: -1

Patrick Roberts
Patrick Roberts

Reputation: 51886

The reason why is because that.bar() is the same thing as bar.call(that), but fn() is the same as fn.call(undefined), and in loose mode, undefined becomes the global context, which is window.

Upvotes: 2

Related Questions