0

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
};
Axel Latvala
  • 576
  • 3
  • 7
  • 21

1 Answers1

2

You can't calling this.sendNOP in ExampleClass.initiate. You are calling it in connect. That the call to connect is inside the initiate function is irrelevant.

You haven't called connect with any context, so the context is the default object (window).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335