use strict 的作用是让 JS 进入到严格模式
在严格模式里面主要有以下特征: use strict;
- 全局变量显式声明
- 禁止使用 with 语句
- 禁止 this 关键字指向全局对象
function f(){ return !this; } // 返回 false,因为"this"指向全局对象,"!this"就是 false function f(){ "use strict"; return !this; } // 返回 true,因为严格模式下,this 的值为 undefined,所以"!this"为 true。
因此,使用构造函数时,如果忘了加 new,this 不再指向全局对象,而是报错。
function f(){ "use strict"; this.a = 1; }; f();// 报错,this 未定义
js 实现只允许构造无法直接调用和只能直接调用无法构造
只允许构造无法直接调用
function obj(){ "use strict"; this.name = 'aaa'; } new obj(); obj(); //报错
只允许直接调用无法构造
function obj(){ try { if( this !== window){ throw new Error(); return false; } }catch(e){ console.dir(e) } } new obj(); //报错 obj()
原理,其实第一种是应用了 js 的严格模式的特性,在严格模式下,直接调用的时候是 obj();其实应该是 window.obj();而严格模式下是不允许 this 直接指向 window 的;
function f(){ "use strict"; return !!this; } f(); 输出:false function f(){ //"use strict"; return !!this; } f(); 输出:true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论