这是一个例子:
function one() {
var a = 1;
two();
function two() {
var b = 2;
three();
function three() {
var c = 3;
alert(a + b + c); // 6
}
}
}
one(); //calling the function
现在,当我们调用函数 one() 时,结果是6
.
所以这都是关于作用域链的,所有变量都已解析,现在我有一个问题。
我们为什么需要这个 ”this当所有变量都通过作用域链解析时“关键字?
所以如果我们有以下函数:
function a() {
var a = 'function a';
function b() {
var b = 'function b';
alert (a); //will be function a, without keyword this
alert (this.a); // what will be the effect of this line
}
}
“this”关键字总是让我感到困惑!
有人请简单详细地解释一下。
他们的关键词this
在 JavaScript 的 a 函数中通过以下方式解决 -
-
当在对象上或通过对象调用函数时,该对象就是调用
函数的上下文或“this”值。例如 -
var o = {
f : function(){
//do something
}
}
如果我们使用对象“o”调用对象“o”的方法“f”-
o.f()// in method f, 'this' refers to o inside the method o
-
如果函数不是在对象上调用或不是通过对象调用,则当前窗口对象是调用上下文或this
函数的值。例如 -
function f(){
//do something
}
//calling f
f();// 'this' will refer to current window object
在您的情况下, this 指的是当前窗口对象并且this.a
是对您在全局范围内定义的函数 a 的引用。
此外,可以在调用函数时提供函数的调用上下文或“this”值。请检查Function.prototype.call 方法- JavaScript | MDN and Function.prototype.apply 方法- JavaScript | MDN
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)