【发布时间】: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