【问题标题】:OOP Javascript 'this' keyword in a nested private method嵌套私有方法中的 OOP Javascript“this”关键字
【发布时间】:2014-05-20 10:46:26
【问题描述】:

下面是一些示例代码:

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

我很好奇为什么我不能在ExampleClass.initiate 中调用this.sendNOP() 以便ExampleClass.initiate._connect()ExampleClass 的instanceof this 作为this 传递给ExampleClass.sendNOP(),似乎将window 作为@ 传递987654329@。为什么?

编辑:

问题是当我们调用ExampleClass.initiate._connect() 时,我们只使用connect(),它没有指定任何上下文。用.apply(this) 调用ExampleClass.initiate._connect() 有效! .apply(this) 将上下文设置为 ExampleClass

ExampleClass.prototype.appliedInitiate = function()
{
    var connect = function()
    {
        this.sendNOP();
    };

    connect.apply(this);
};

最终代码

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

【问题讨论】:

    标签: javascript oop this


    【解决方案1】:

    您不能在ExampleClass.initiate 中调用this.sendNOP。您在connect 中调用它。对connect 的调用在initiate 函数内部是无关紧要的。

    您没有使用任何上下文调用connect,因此上下文是默认对象 (window)。

    【讨论】:

    • +1 以及我最喜欢的 SO javascript 问题之一:stackoverflow.com/questions/3127429/javascript-this-keyword
    • 使用.apply() 调用connect 似乎并没有改变任何事情。我应该如何优雅地解决这个问题?
    • 应该可以。你是怎么用的?
    • 你怎么打电话给ExampleClass
    • @Quentin 我是通过构造函数来做的; exc = new ExampleClass()
    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2013-12-01
    相关资源
    最近更新 更多