• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem understanding this

 
simon tiberius
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


what do "this" in ??1 and ??2 refer to? the function.prototype? the anonymous function within which "this" is declared? or any object calling the function? or what? thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65123
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an example from chapter 5 on closures from Secrets of the JavaScript Ninja. It's sort of difficult for anyone to understand out of context. It shows how to use closures to use currying in JavaScript.

Because partial is a method placed on the Function prototype, it will be invoked on a function and hence, the function context (the first this) of the method will be that function. We store that in the fn variable for later reference.

The second this is within the anonymous function that we return as the result, and hence it refers to whatever function context is assigned to that function when it is called. We don't know what it is and we don't care. (Remember, the function context is determined by how the function is called, not by how it is declared.) We just make it the function context of the curried function by passing it as the first parameter to apply().
 
simon tiberius
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so, both this refer to different entity? could you please give me an sample code that makes use of this partial function? perhaps I can understand more which "this" refers to what. Thanks a lot.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65123
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simon tiberius wrote:so, both this refer to different entity?

Yes. Notice that they are within different functions. Each function invocation has it's own function context (this). And the function context (this) is not shared as part of a closure.

Could you please give me an sample code that makes use of this partial function? perhaps I can understand more which "this" refers to what.

Since you posted the code, I assume that you have bought a copy of the MEAP book. Please read that section thoroughly.
 
simon tiberius
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this is the code from the book. I wanted another example since I'm still not very familiar with timer function in javascript and the book used setTimeout. So, what do the first and second this refer to in this code?
my guess is ??1 refers to setTimeout, and I really have no idea what ??2 refers to.
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic