简体   繁体   中英

OOP Javascript 'this' keyword in a nested private method

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
};

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM