Introduction
JavaScript sets a value of the execution context, "this", during execution.
Use cases/mistakes
For an example, we use a Menu constructor, that should accept an element and create a menu on it’s base as in the following:
- function Menu(elem) {
- // ...
- }
- // Usage
- var elem = document.getElementById('Abhijeet') // a DOM element
- var menu = new Menu(elem)
When you setup setTimeout, you may want it to reference the object:
- function Mymenu(elem) {
- setTimeout(function () {
- alert(this) // window, not menu!
- }, 1000)
- }
- new Mymenu(document.createElement('div'))
But this references the window because setTimeout always executes the function in the window context.
A simple call to privateMethod() uses "this" as the window.
- function Mymenu(elem) {
- function privateMethod() {
- alert(this) // window, not menu!
- }
- // ... call private method
- privateMethod()
- }
- new Mymenu(document.createElement('div'))
In the following example, "this" is copied to a new variable "abhi". This variable is then used instead of "this".
- function Mymenu(elem) {
- var abhi = this
- setTimeout(function () {
- alert(abhi) // object! (menu)
- }, 1000)
- }
- new Mymenu(document.createElement('div'))
Early binding
For example:
- function bind(func, fixThis) {
- return function () {
- return func.apply(fixThis, arguments)
- }
- }
Late binding
For example:
- <!DOCTYLE HTML>
- <html>
- <body>
- <script>
- function bindLate(funcName, fixThis) { // instead of bind
- return function () {
- return fixThis[funcName].apply(fixThis, arguments)
- }
- }
- function Mymenu(elem) {
- this.Hello = function () { alert('Mymenu') }
- elem.onclick = bindLate('Hello', this)
- }
- function BigMenu(elem) {
- Mymenu.apply(this, arguments)
- this.Hello = function () { alert('BigMenu') }
- }
- new BigMenu(document.body)
- </script>
- Click here. I'm a BigMenu!
- </body>
- </html>

Jaganathan BantheswaranPosted Feb 19, 2014, 12:34 AM
You might be inspired by some other article[http://javascript.info/tutorial/binding] but you have to provide your own version when you post it on public community like C#Corner...
Jaganathan BantheswaranPosted Feb 12, 2014, 7:47 AM
We can do the same thing with JS's bind method like this http://jsfiddle.net/Jaganathan/LLV8u/
Abhijeet SinghPosted Feb 12, 2014, 6:39 AM
The wrapper created by bindLate() resolves the object method at calling time so we can say that bindLate() works for object methods only.....for example : if we use elem.onclick = bind(this.Hello, this) in place of bindLate('Hello', this) then It outputs “Mymenu” on click, but it should output “BigMenu”.
Jaganathan BantheswaranPosted Feb 12, 2014, 1:27 AM
You must be aware of JS native function bind() which does the same thing as you described here. May i know what is the difference between JS's bind() and yours bindLate() ?