I’m new to prototype-based languages and have read this question:
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 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?
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
thisvalue is stored), and thethisvalue is implicitly set when you invoke a function, and if a function reference has no base object (e.g.foo();, vsobj.foo()), the global object will set as thethisvalue 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
nextCallbackmethod 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: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: