views:

71

answers:

3

I'm new to prototype based languages and have read this question:

http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions

I'm wondering what value there is, of using a prototype based signature to attach methods to an object. Why not just attach the method to the object's property in the object's definition?

Second, when using the the prototype signature to define methods on an object, why does the 'this' pointer resolve to the window object inside the function? This appears to be a design flaw. If it's not could someone explain, or point me to an explanation regarding why not?

Thank you.

Edit:

This code performs as expected, rendering a message box with the word 'here' inside.

function Obj()
{   
    this.theVar = 'here';
    this.method2 = function(){ alert( this.theVar ); }
}

Obj.prototype.method3 = function(){ this.method2(); }
Obj.prototype.method4 = function(){ this.method3(); }

var obj = new Obj();
obj.method4();

This code is my AJAX callback, and the 'this' pointer refers to the 'window' object during execution.

Test.prototype.nextCallback = function( response )
{
    if( response.Status != 'SUCCESS' )
        show_message( response.Message, false );
    else
        this.setQuestion( response.Question );
}

Test.prototype.setQuestion = function( question ){ ... }

The 'this' pointer actually works properly before the AJAX call, but not after. Is this result because the nextCallback() context is not properly restored after the AJAX call returns and before the callback is called? Is there a way to remedy this?

A: 
  1. In JavaScript, if you use a function as a constructor, to create new objects, then assigning a method to this in the constructor means that each new object gets a new method defined. Assigning to the prototype means that you only get one definition of the method, in the prototype.

  2. Yes, this pointing to the global object in some cases is a design flaw, but I didn't think that in the case you mention this happens.

If you want to learn best practices in JavaScript objects and prototypal inheritance, watch Douglas Crockford's videos.

Skilldrick
Thanks Skilldrick, I'll definitely check out those videos.
Andrew
A: 

1- The point of adding members on a constructor's prototype, is behavior reuse.

All object instances that inherit from that prototype, will be able to resolve the member through the prototype chain, also the members are defined only once, not in every instance.

2- This happens because each function has its own execution context (that's where the this value is stored), and the this value is implicitly set when you invoke a function, and if a function reference has no base object (e.g. foo();, vs obj.foo()), the global object will set as the this value inside the invoked method.

See the second part of this answer for more details.

Edit: After looking your code, seems that you are passing a reference of the nextCallback method as the callback function of some Ajax success event, if it's so, the base object of the reference will be lost, a common approach that can be to use an anonymous function that invokes correctly your method, for example:

var obj = new Test();
//...
someAjaxLib(url, function (data) {
  obj.nextCallback(data); // `this` will refer to obj within nextCallback
});

Another approach can be to bind a method to its instance within the constructor, keep in mind that the method will be defined as an own property on each object instance you create, it will not be inherited, for example:

function Test() {
  var instance = this; // store reference to the current instance

  this.nextCallback = function( response ) {
    if( response.Status != 'SUCCESS' ) {
      show_message( response.Message, false );
    } else {
      instance.setQuestion( response.Question ); // use the stored reference
    }
  }
}
CMS
Thanks for responding CMS. You seem to have in-depth knowledge of the topic and I'd like to post a little more code show you what I'm trying to accomplish. I'll post it an answer below so it's a little more readable.
Andrew
@Andrew, I have seen your code, give a look to my response.
CMS
I concur. See my answer below.
Andrew
A: 

In my case it appears that when the method is added to an object via a prototype signature, and subsequently passed for use as an AJAX callback method, that method is then re-scoped to the global object (window) and loses its original context. That is to say, the method is no longer a member of the prototype on which it was defined.

I've only tested this in Firefox. I'm guessing this behavior is because the AJAX call is physically executed on a different OS thread, and upon return from the AJAX call the specified callback method is found and executed. No attempt is made to resolve the original context of the method between threads. Again this is just a guess.

Andrew
It has to do about how the method is invoked, since you pass only a reference to it, the Ajax library will invoke usually an argument, without any base object info, e.g.: `var t = new Test(), m = t.nextCallback; m();` In the previous example `m` refers to the method, just like if you pass it as an argument, invoking `m();` will set the `this` value to the global object.
CMS