我试图理解为什么在javascript中,您可能想要更改函数的上下文.我正在寻找一个真实世界的例子或某些东西,它将帮助我理解这项技术的使用方式/原因以及它的意义.
使用此示例说明了该技术(来自http://ejohn.org/apps/learn/#25)
var object = {};
function fn(){
return this;
}
assert( fn() == this, "The context is the global object." );
assert( fn.call(object) == object, "The context is changed to a specific object." );
Run Code Online (Sandbox Code Playgroud) 这取自John Resig的Learning Advanced Javascript#25,称为更改函数的上下文.
1)在这行中fn() == this是指什么?它是指在函数里面说它返回这个吗?
2)虽然我理解了最后一行的目的(将函数附加到特定对象),但我不明白代码是如何做到的."call"这个词是预定义的JavaScript函数吗?用简单的语言,请解释"fn.call(object)",并明确地告诉我parens (object)中的对象是否与对象相同var object.
3).将函数分配给对象后,是否可以通过写入来调用该函数object.fn();?
var object = {};
function fn(){
return this;
}
assert( fn() == this, "The context is the global object." );
assert( fn.call(object) == object, "The context is changed to a specific object."
Run Code Online (Sandbox Code Playgroud)