Pri*_*ank 2 javascript scope this
嗨,我有以下我试图运行的JavaScript代码.我的目标是掌握this
JavaScript中不同范围和不同类型的调用的含义.
如果你查看下面的代码:我有一个内部匿名函数,它被赋值给innerStuff
变量.在那个匿名函数中,这样this
指向window
对象而不是外部函数对象或其他任何东西.事件虽然它仍然可以访问函数的变量.
无论如何,我不确定,为什么会这样; 但是如果你看下面的代码,我会以后的this
形式传递that
给innerStuff
它,它可以正常运行并doofus
在控制台中打印带有属性的对象.
var someStuff = {
doofus:"whatever",
newF: function()
{
var that = this;
console.log(that);
var innerStuff = function(topThis){
console.log(topThis);
};
return innerStuff(that);
}
}
someStuff.newF();
Run Code Online (Sandbox Code Playgroud)
现在我只是改变了一点代码.而不是分配它innerStuff
,我只是通过调用它直接返回该函数,如下所示:
var someStuff = {
doofus:"whatever",
newF: function()
{
var that = this;
console.log(that);
return function(that){
console.log(that);
}();
}
}
someStuff.newF();
Run Code Online (Sandbox Code Playgroud)
这打印内部匿名函数未定义.是因为that
作为参数传递的内容与that
外部函数中定义的内容之间存在冲突吗?我认为参数会覆盖可见性.为什么价值不会保留?
这完全令人困惑.
另一方面,如果我没有通过that
,而只是使用它,因为可见性存在,结果是正确的和预期的.
我错过了什么?它是变量之间的冲突,存在于相同的范围内吗?有没有一个很好的理由,内部函数this
必然会受到window
反对?
this
在JavaScript中引用您调用方法的对象.如果调用函数someObject.functionName(args)
,this
则将绑定到该对象.如果只是调用一个裸函数,就像在中functionName(args)
,那么this
将绑定到该window
对象.
在newF
第二个例子中,你that
在内部函数中隐藏变量,但没有将任何内容传递给它,所以它是未定义的.
var that = this;
console.log(that);
return function(that){
console.log(that);
}();
Run Code Online (Sandbox Code Playgroud)
您可能需要以下内容,如果您想要的东西与第一个示例相同(传入that
内部函数):
var that = this;
console.log(that);
return function(that){
console.log(that);
}(that);
Run Code Online (Sandbox Code Playgroud)
或者以下,如果您不想隐藏它并只使用外部函数的绑定:
var that = this;
console.log(that);
return function(){
console.log(that);
}();
Run Code Online (Sandbox Code Playgroud)