ECMA-262-3 深入理会.第三章.this[译]
|
导言 在这篇文章中我们将接头一个与执行上下文直接相干各更多细节。接头的主题就是this要害字。 实践表白,这个主题很难,在差异执行上下文中this值简直定常常导致题目。 很多措施员风俗的以为,在措施说话中,this要害字与面向工具的措施细密相干,完全指向通过结构器建设的新的工具。在ECMAScript中也是这样执行的,但正如你看到的那样,这并不限于建设工具的界说。 让我们更具体的相识ECMAScript中真正的this值是什么? 界说 这个值是执行上下文中的一个属性。 activeExecutionContext = {
VO: {...},
this: thisValue
};
这里VO使我们前面接头的变量工具。 this与上下文中可执行代码亲近直接相干,这个值取决于进入的上下文,代码在上下文中运行时一成稳固 全局代码中的this值 在这里统统都简朴。在全局代码中,this始终是全局工具自己,这样有也许间接的引用它。 // explicit property definition of // the global object this.a = 10; // global.a = 10 alert(a); // 10 // implicit definition via assigning // to unqualified identifier b = 20; alert(this.b); // 20 // also implicit via variable declaration // because variable object of the global context // is the global object itself var c = 30; alert(this.c); // 30 函数代码中的this值 在函数代码中行使this 时很风趣,这种环境很难且会导致许多题目。 这种范例的代码中,this值的主要特点(或者是最首要的)是它不是静态的绑定到一个函数。 正如我们上面曾提到的那样,这个值取决于进入的上下文,在一个函数代码中,这个值在每一次完全差异。 可是,在代码运行时的this值是稳固的,也就是说,既然它不是一个变量,就不行能为其分派一个新值(相反,在Python编程说话中,它明晰的界说为工具自己,在运行时代可以不绝改变)。 var foo = {x: 10};
var bar = {
x: 20,
test: function () {
alert(this === bar); // true
alert(this.x); // 20
this = foo; // error
alert(this.x); // if there wasn't an error then 20, not 10
}
};
// on entering the context this value is
// determined as "bar" object; why so - will
// be discussed below in detail
bar.test(); // true, 20
foo.test = bar.test;
// however here this value will now refer
// to "foo" – even though we're calling the same function
foo.test(); // false, 10
(编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

