Here is some example code:
ExampleClass = function()
{
this.initiate();
};
ExampleClass.prototype.initiate = function()
{
var connect = function()
{
this.sendNOP();
};
connect();
};
ExampleClass.prototype.sendNOP = function()
{
console.info('Sending NOP...');
var callback = function()
{
console.info('Server responded to NOP. ZzzZzzzZzz...');
};
setTimeout(callback, 1500);
};
I am very curious why I can't call this.sendNOP() in ExampleClass.initiate so that ExampleClass.initiate._connect() will pass the instanceof ExampleClass as this to ExampleClass.sendNOP(), it seems to pass window as this. Why?
EDIT:
The problem is when we call ExampleClass.initiate._connect() we only use connect() which does not specify any context. Calling ExampleClass.initiate._connect() with .apply(this) works! .apply(this) sets the context to ExampleClass.
ExampleClass.prototype.appliedInitiate = function()
{
var connect = function()
{
this.sendNOP();
};
connect.apply(this);
};
Final code
ExampleClass = function()
{
this.appliedInitiate();
};
ExampleClass.prototype.sendNOP = function()
{
console.info('Sending NOP...');
var callback = function()
{
console.info('Server responded to NOP. ZzzZzzzZzz...');
};
setTimeout(callback, 1500);
};
ExampleClass.prototype.initiate = function()
{
var connect = function()
{
this.sendNOP();
};
connect(); // Won't work. connect() is not called from any context (ie. obj.connect() )
};
ExampleClass.prototype.appliedInitiate = function()
{
var connect = function()
{
this.sendNOP();
};
connect.apply(this); // Will work, we are calling connect with apply, which sets the context to ExampleClass
};