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
(编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |