陷阱:shadowing this
最佳实践
this 在办法中
在办法中,类似于传统的面向对象的说话:this指向接收者,办法被调用的对象。
- var obj = {
- method: function () {
- console.log(this === obj); // true
- }
- }
- obj.method();
在Node.js中,平日在模块中履行代码。 是以,顶级感化域是一个特别的模块感化域:
在浏览器中,顶层感化域是全局感化域,它指向 global object(如window):
- console.log(this === window); // true
- // `global` (不是 `window`) 指全局对象:
- console.log(Math === global.Math); // true
- // `this` 不指向全局对象:
- console.log(this !== global); // true
- // `this` refers to a module’s exports:
- console.log(this === module.exports); // true
this 在 eval() 中
eval() 可以被直接(经由过程真正的函数调用)或借居(经由过程其他方法)调用。
如不雅借居调用evaleval() ,则this指向全局对象:
- (0,eval)('this === window')
- true
不然,如不雅直接调用eval() ,则this与eval()的情况中保持一致。 例如:
- // 通俗函数
- function sloppyFunc() {
- console.log(eval('this') === window); // true
- }
- sloppyFunc();
- function strictFunc() {
- 'use strict';
- console.log(eval('this') === undefined); // true
- }
- strictFunc();
- // 构造器
推荐阅读
有奖调研 | 人脸辨认功能在互联网行业认知度情况经由过程应用法度榜样级其余感知和洞察,为微办事带来编排和主动化的优势 微软的 Azure Service Fabric 的官方博客在2017.3.2>>>详细阅读
本文标题:JavaScript中this的运行机制及爬坑指南
地址:http://www.17bianji.com/lsqh/40750.html
1/2 1