Understanding Javascript's difference between calling a function, and returning the function but executing it later.

Posted by Squeegy on Stack Overflow See other posts from Stack Overflow or by Squeegy
Published on 2011-01-10T01:36:33Z Indexed on 2011/01/10 1:53 UTC
Read the original article Hit count: 506

Filed under:
|
|
|

I'm trying to understand the difference between foo.bar() and var fn = foo.bar; fn();

I've put together a little example, but I dont totally understand why the failing ones actually fail.

var Dog = function() {
    this.bark = "Arf";
};

Dog.prototype.woof = function() {
    $('ul').append('<li>'+ this.bark +'</li>');
};

var dog = new Dog();


// works, obviously
dog.woof();

// works
(dog.woof)();

// FAILS
var fnWoof = dog.woof;
fnWoof();


// works
setTimeout(function() {
    dog.woof();
}, 0);

// FAILS
setTimeout(dog.woof, 0);

Which produces:

  • Arf
  • Arf
  • undefined
  • Arf
  • undefined

On JSFiddle: http://jsfiddle.net/D6Vdg/1/

So it appears that snapping off a function causes it to remove it's context. Ok. But why then does (dog.woof)(); work?

It's all just a bit confusing figuring out whats going on here. There are obviously some core semantics I'm just not getting.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about prototype