这里是一些示例代码:
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()
code> 会将 ExampleClass
的实例作为 this
传递给 ExampleClass.sendNOP()
,它似乎将 window
传递为这个
。为什么?
编辑:
问题是当我们调用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
};
最佳答案
您无法在 ExampleClass.initiate
中调用 this.sendNOP
。您在 connect
中调用它。对 connect
的调用位于 initiate
函数内部是无关紧要的。
您尚未使用任何上下文调用 connect
,因此上下文是默认对象 (window
)。
关于javascript - 嵌套私有(private)方法中的 OOP Javascript 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757666/